user2632918
user2632918

Reputation:

Create an array in swift

I'm searching really much, but maybe I can't understand the results.

I found only that a array in SWIFT have as index int-values

var myArray = [String]()

myArray.append("bla")
myArray.append("blub")

println(myArray[0]) // -> print the result   bla

But I will add a String with an String as index-key

var myArray = [String:String]()

myArray.append("Comment1":"bla")
myArray.append("Comment2":"blub")

println(myArray["Comment1"]) // -> should print the result bla

How should i declare the array and how I can append a value then to this array?

Upvotes: 0

Views: 171

Answers (3)

Bug Hunter Zoro
Bug Hunter Zoro

Reputation: 1915

You got the concept of array in the first example but for the second one you need a dictionary as they operate on key value pair

// the first String denotes the key while the other denotes the value
var myDictionary :[String:String] = ["username":"NSDumb"]
let value = myDictionary["username"]!;
println(value)

Quick reference for dictionaries collection type can be found here

Upvotes: 0

IxPaka
IxPaka

Reputation: 2008

Your second example is dictionary

myArray["key"] = "value"

If you want array of dictionaries you would have to declare it like this

var myArray: [[String: String]]

Upvotes: 2

Fogmeister
Fogmeister

Reputation: 77661

Your first example is an array. Your second example is a dictionary.

For a dictionary you use key value pairing...

myArray["Comment1"] = "Blah"

You use the same to fetch values...

let value = myArray["Comment1"]
println(value)

Upvotes: 1

Related Questions