With swift, the multidimensional array doesn't work the way you want it to.

Asked 2 years ago, Updated 2 years ago, 37 views

Nice to meet you

 vara=[String]()

a. insert("a", atIndex:0)
a.append("b")
a+=["c"]


Something like
I'd like to have multiple arrays.

 varb=[String]]()

a[0].insert("a", atIndex:0)
a[1].append("b")
a[2]+=["c"]

Compilation passed, but
The following error appears in this part:

 fatal error:Array index out of range

When I try playground, there is no error, but it does not work.

I don't see many descriptions of multidimensional arrays, so I asked you a question.
Thank you for your cooperation.

swift xcode

2022-09-29 22:37

2 Answers

The contents of the multidimensional array have not been initialized.

 varb: [[String]] = [[], [], []]

b[0].insert("a", atIndex:0)
b[1].append("b")
b[2] = ["c"]


2022-09-29 22:37

In the Playground of Xcode 6.3, the members of the array appear to be immutable.I don't know if it's a bug, but you have to be careful because the behavior is different from other environments other than Playground.

This is the best way to initialize a two-dimensional array.

var stringArray=[String]]()
US>stringArray.append([String]())
US>stringArray.insert ([String]( ), atIndex: 1)
US>stringArray+=[[["c"]]

US>stringArray[0].append("a")
US>stringArray[1].insert("b", atIndex:0)
US>stringArray[2]+=["d"]

println(stringArray.description)

Output:

[[a], [b], [c, d]]


2022-09-29 22:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.