Spielekind005
Spielekind005

Reputation: 47

Is there a way to store arrays in an array in Swift

I want to store a few arrays that contain Strings in an array. When I want to initialize it I get this error:

Cannot convert value of type '[Any]' to specified type '[Array]' Insert' as![Array]​'.

array is created like this:

    var array: [String] = []

I already tried:

var bigArray: [Array] = []
bigArray.append(array)

or like this:

var bigArray: [Array] = [Array]
bigArray.append(array)

and this:

var bigArray: [Array] = [Array]as!Array
bigArray.append(array)

Upvotes: 0

Views: 1482

Answers (3)

Razi Tiwana
Razi Tiwana

Reputation: 1435

Simply try

var array: [[String]] = []

then you can add arrays like

let firstArray = ["one", "two"]
array.append(firstArray)

Upvotes: 1

puzzle
puzzle

Reputation: 6131

You're missing a second set of brackets. If you want to make an array of arrays of strings it needs to be of type [[String]] not [String]:

let fruits1 = ["Apples", "Oranges"]
let fruits2 = ["Bananas", "Strawberries", "Cherries"]

var fruitbaskets: [[String]] = []

fruitbaskets.append(fruits1)
fruitbaskets.append(fruits2)

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

If you want an array of string arrays then simply do:

var bigArray = [[String]]()
bigArray.append(array)

Upvotes: 2

Related Questions