How to use for loop to create int array in Swift 3

I know this is a very simple question,

But I try many methods and always show:

"fatal error: array index out of range"

I want to create an array 0 ~ 100 int

eq var integerArray = [0,1,2,3, ....., 100]

and i try

var integerArray = [Int]()
for i in 0 ... 100{
integerArray[i] = i
}

Also appear: fatal error: array index out of range

thanks for the help

Full 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
    }
}
+4
source share
2 answers

Your array is empty, and you subscribe to a subscription to assign a value, which causes you to crash "Array index out of range." If you want to go with for loopthat.

var integerArray = [Int]()
for i in 0...100 {
    integerArray.append(i)
}

, for loop.

var integerArray = [Int](0...100)
+12

, , "integerArray[i] ( i 1)" .

- :

 func giveArrayNumber() {
    for i in 0 ... 100{
       integerArray.append(i)
    }
 }
0

Source: https://habr.com/ru/post/1671870/


All Articles