简体   繁体   中英

Array of arrays in Swift

I want to make and array that contains arrays, some are of double's, some are of int's.

This does not work:

var arrayZero = [1,2,3]
var arrayOne = [4.0,5.0,6.0]

var arrayofArrayZeroandOne: [[AnyObject]] = arrayZero.append(arrayOne)

How can I append arrays to an array so that I can get 5.0 if I write arrayofArrayZeroandOne[1][1] ?

I would take advantage of Swift's type safety. Going the Any route could introduce bugs if you're not careful adding and retrieving from the array.

var numbers = Array<Array<NSNumber>>()  // A bit clearer IMO
var numbers = [[NSNumber]]()            // Another way to declare
numbers.append(arrayZero)
numbers.append(arrayOne)

Then when you do something like

let five = numbers[1][1] // will be 5.0

You know it will be of type NSNumber. Further Swift won't let you put anything else into the array unless it's an NSNumber

Without appends solution

var numbers = Array<Array<NSNumber>>() [
    [1,2,3,4],
    [1.0,2.0,3.0,4.0]
]

You're looking for [[Any]] (and note that append mutates in place):

let arrayZero = [1, 2, 3]
let arrayOne = [4.0, 5.0, 6.0]

let arrayofArrayZeroAndOne: [[Any]] = [arrayZero, arrayOne]

let a = arrayofArrayZeroAndOne[0][0] // of type Any

You do not need an append, you can construct the array directly:

var arrayZero = [1, 2, 3]
var arrayOne = [4.0, 5.0, 6.0]
var arrayofArrayZeroandOne: [[AnyObject]] = [arrayZero, arrayOne]

println(arrayofArrayZeroandOne[1][1]) // Prints 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM