1

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

3 Answers 3

4

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]
]
Sign up to request clarification or add additional context in comments.

5 Comments

Great, this is the answer closest to what I was asking for - Thanks to all of you !
In your example, if I try to add numbers[10] = [8,9,10] for example. I get an error. I guess it is because it has not been initialised to be that size yet, so there is no space yet for index=10. But how could I do that, initialise the array to hold say tableViewRows.count.. arrays?
Well you'll have to execute a loop over the number of rows in your tableView and append more arrays of NSNumbers
Ahh, yes, sorry - shortcut here, figured it out :-) for i in 0...10{ numbers.append([NSNumber]()) }
actually this is a bit cleaner I guess: var numbers = Array(count: tableViewRows.count, repeatedValue:[NSNumber]())
1

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

1 Comment

I get an error when I do that in playground "Execution was interrupted, reason: EXC_BAD_ACCESS(Code=1, address=0x1).
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.