Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 865
JimmyHo Avatar asked Mar 09 '17 09:03

JimmyHo


2 Answers

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)
like image 91
Nirav D Avatar answered Nov 15 '22 06:11

Nirav D


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) }
like image 2
Andrew Avatar answered Nov 15 '22 06:11

Andrew