-1

In Swift 3 playground, I want to create a mutable array with numbers at some indices and Strings at others. I get errors doing this:

var playerInfo = [[String]]()
playerInfo[0][2] = "Adam" //Error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)
playerInfo[0][3] = "Martinez"
playerInfo[0][1] = "00"

EDIT: Something like this?

var playerInfo: [[String:Any]] = [
     [
     "playerNumber" : "00",
     "playerFirstName" : "Adam",
     "playerLastName" : "Martinez"
     ]
]
  • You can create array of dictionary for this. – Sagar Chauhan Mar 28 '17 at 08:17
  • You cannot add items with index subscripting because all arrays are empty (no index 0). – vadian Mar 28 '17 at 08:20
  • I just answered another question like this: [How to create an Array or Dictionary whose values can only be String, Int and Boolean?](http://stackoverflow.com/questions/43061928/how-to-create-an-array-or-dictionary-whose-values-can-only-be-string-int-and-bo/). – Nandin Borjigin Mar 28 '17 at 08:20
  • 1
    @NandiinBao The reason of the crash is not related to your linked answer. – vadian Mar 28 '17 at 08:21
  • As for the crash, @vadian is right. `var playerInfo = [[String]]()` only creates an empty array of empty arrays. `playerInfo[0]` would cause crash because there is no 0-th element in `playerInfo` since it's empty. Also even you construct the variable as `var playerInfo = [[String]](repeating: [], count: 100)`, calling `playerInfo[0][2]` would also cause crash. `playerInfo[0]` does exist this time, but it's an empty array, there is no 2-nd element in it. – Nandin Borjigin Mar 28 '17 at 08:48

1 Answers1

1

You are not using the syntax correctly.

Try this:

var playerInfo = [[String]]()
playerInfo.append(["00","Adam","Martinez"])

EDIT

For your edit, you need a Dictionary:

var playerInfo = Dictionary<String, Any>()

playerInfo["playerNumber"] = "00"
playerInfo["playerFirstName"] = "Adam"
playerInfo["playerLastName"] = "Martinez"
Aitor Pagán
  • 423
  • 7
  • 18