0

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?

2
  • 1
    Did you read the chapter "Collection Types" in The Swift Programming Language ? Commented Mar 19, 2015 at 10:31
  • What does this have to do with the xcode IDE? Commented Mar 19, 2015 at 10:32

3 Answers 3

2

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

Comments

1

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)

2 Comments

Aha, thats the difference. Thank you for this information
No worries. Of course, I'd maybe call it something else. Using the name "Array" for a dictionary could be confusing :-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.