I know this is a very basic question,
But I try lot methods, and always show:
"fatal error: Array index out of range"
I want to create a 0~100 int array
e.q. var integerArray = [0,1,2,3,.....,100]
and I trying
var integerArray = [Int]()
for i in 0 ... 100{
integerArray[i] = i
}
There are also appear : fatal error: Array index out of range
Thanks for help
Complete code:
class AlertViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var integerPickerView: UIPickerView!
@IBOutlet weak var decimalPickerView: UIPickerView!
var integerArray = [Int]()
var decimalArray = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
giveArrayNumber()
integerPickerView.delegate = self
decimalPickerView.delegate = self
integerPickerView.dataSource = self
decimalPickerView.dataSource = self
}
func giveArrayNumber(){
for i in 0 ... 100{
integerArray[i] = i
}
}
Your array is empty and you are subscripting to assign value thats why you are getting "Array index out of range" crash. If you want to go with for loop
then.
var integerArray = [Int]()
for i in 0...100 {
integerArray.append(i)
}
But instead of that you can create array simply like this no need to use for loop
.
var integerArray = [Int](0...100)
Without using loops:
var integerArray = Array(0...100)
Without using loops 2:
var integerArray = (0...100).map{ $0 }
Without using loops 3:
var integerArray = [Int](0...100)
Using loops (better do not use) :
var integerArray = [Int]()
for i in 0...100 { integerArray.append(i) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With