12

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
    }
}
1
  • 2
    Reading the documentation helps: "You can add a new item to the end of an array by calling the array’s append(_:) method:" and "You can’t use subscript syntax to append a new item to the end of an array." Commented Mar 9, 2017 at 10:04

3 Answers 3

33

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@JimmyHo Welcome mate :)
4

Solution 1:

var integerArray = Array(0...100)

Solution 2:

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

Solution 3(worst):

var integerArray = (0...100).map{ $0 }

1 Comment

The accepted answer is good but I think this is much more useful in general :)
0

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)
    }
 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.