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
eq 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:
var integerArray = [Int]()
for i in 0...100 { integerArray.append(i) }
Because your array is empty, so the " integerArray[i]
(where i
is 1 for example)" doesn't exist.
You have to write something like this :
func giveArrayNumber() {
for i in 0 ... 100{
integerArray.append(i)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.