# 2D array Index out of range error

**URL:** <https://forums.kodeco.com/t/2d-array-index-out-of-range-error/42077>\
**Category:** Swift\
**Created:** [April 30, 2018, 10:33am UTC](https://forums.kodeco.com/t/2d-array-index-out-of-range-error/42077 "2018-04-30T10:33:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![milad](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/milad/32/79544_2.png) [@milad](https://forums.kodeco.com/u/milad)\
**Post date:** [April 30, 2018, 10:33am UTC](https://forums.kodeco.com/t/2d-array-index-out-of-range-error/42077/1 "2018-04-30T10:33:28Z")

</div>

I’m trying to read 2D array values from keyboard

 ![46%20PM](https://raywenderlich-com-v3-forums.s3.amazonaws.com/original/3X/3/6/36f70a380a6bb2bc1d5fedd74978042def636a5a.png)

---

<div class="post-metadata">

**Author:** ![jayantvarma](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/jayantvarma/32/111768_2.png) [@jayantvarma](https://forums.kodeco.com/u/jayantvarma)\
**Post date:** [April 30, 2018, 1:27pm UTC](https://forums.kodeco.com/t/2d-array-index-out-of-range-error/42077/2 "2018-04-30T13:27:39Z")

</div>

Hi @milad,  
a couple of things, why are you trying to explicitly unwrap using the !? instead you can wrap them in an if which will not only unwrap but also give you error handling, like

```auto
if let input = readLine(), let vertexCount = Int(input) {
  // The main program comes here
}

```

The second thing is the way you are looping to get values, it is not clear on which way you are trying to get values. One would assume that since these are 2D values, you are expecting a `x,y` type of values instead here you are getting y (0…\<max) x (0…\<max) looped

Lastly, your main question, the code is crashing because you are trying to save data into an array that is not allocated.

this is the way you can get the code to work,

```auto
import Foundation

print("Enter vertex count > ", terminator: "")

if let input = readLine(), let vertexCount = Int(input) {
	var matrixAdjancy = [[Int]]()

	for i in 0..<vertexCount {
		var jArray:[Int] = []
		for j in 0..<vertexCount {
			print("Enter a number for \(i), \(j) > ", terminator: "")
			if let input = readLine(), let inputNumber = Int(input) {
				jArray.append(inputNumber)
			} else {
				print(" ***Entered non number***")
			}
		}
		matrixAdjancy.append(jArray)
	}

	print(matrixAdjancy)

} else {
	print(" You have not entered a valid number")
}

```

cheers,

Jayant

---

<div class="post-metadata">

**Author:** ![system](https://s3.amazonaws.com/cdn.raywenderlich.com/community/forum-assets/noun-game-ghost-878668.png) [@system](https://forums.kodeco.com/u/system)\
**Post date:** [October 14, 2018, 2:38am UTC](https://forums.kodeco.com/t/2d-array-index-out-of-range-error/42077/3 "2018-10-14T02:38:20Z")

</div>

This topic was automatically closed after 166 days. New replies are no longer allowed.
