[英]How to use for loop to create Int array in Swift 3
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我想创建一个 0~100 int 数组
eq var integerArray = [0,1,2,3,.....,100] 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还有出现: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.如果你想使用
for loop
然后。
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
.但是,您可以像这样简单地创建数组,而无需使用
for loop
。
var integerArray = [Int](0...100)
Without using loops:不使用循环:
var integerArray = Array(0...100)
Without using loops 2:不使用循环 2:
var integerArray = (0...100).map{ $0 }
Without using loops 3:不使用循环 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.因为你的数组是空的,所以“
integerArray[i]
(例如,其中i
是 1)”不存在。
You have to write something like this :你必须写这样的东西:
func giveArrayNumber() {
for i in 0 ... 100{
integerArray.append(i)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.