KML
KML

Reputation: 2322

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] ?

Upvotes: 1

Views: 926

Answers (3)

aahrens
aahrens

Reputation: 5590

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]
]

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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

Upvotes: 1

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

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

Upvotes: 1

Related Questions