Seb
Seb

Reputation: 1113

"Extract" array from dictionary in swift

I'm pretty new to Swift and need your help on a (probably) pretty basic problem.

I have a dictionairy:

var dict = ["title" : "Title", "Features" : ["feat1", "feat2", "feat3"], ...]

I can create a string from it like so:

var headline = dict["title"]! as string

but I couldn't manage to create an array. I tried in various combinations:

var features = dict["Features"]
var features = dict["Features"]! as Array
var features: Array = dict["Features"]

So please enlighten me! How do create an array? Is it possible at all?

Upvotes: 0

Views: 288

Answers (2)

ad121
ad121

Reputation: 2368

Your problem is that you don't have a type for the array. You describe the type of an array in swift by putting the type name in brackets. In your case, this will be [String]. Thus, your code should be var features = dict["Features"] as [String] for a mutable array, or use let for an immutable array. Hope this helps.

Upvotes: 1

Rob
Rob

Reputation: 437702

You should specify the type for the array. Either

let features = dict["Features"] as [String] 

or

let features = dict["Features"] as Array<String>

See the discussion of collection types in The Swift Language.

Upvotes: 2

Related Questions