在swift中创建数组

问题描述:

我在寻找真的很多,但也许我无法理解结果。在swift中创建数组

我发现只有在SWIFT一个阵列具有与指数INT值

var myArray = [String]() 

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

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

但我将添加一个字符串的字符串作为索引键

var myArray = [String:String]() 

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

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

我应该如何申报数组,以及我可以如何将一个值附加到这个数组?

+1

您是否阅读过[Swift编程语言](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/)中的“集合类型”一章? – 2015-03-19 10:31:36

+0

这与'xcode IDE'有什么关系? – Popeye 2015-03-19 10:32:04

你的第二个例子是字典

myArray["key"] = "value" 

如果你想要一些字典,你将不得不像这样宣布它

var myArray: [[String: String]] 

你的第一个例子是一个数组。你的第二个例子是一本字典。

对于您使用的键值配对的字典...

myArray["Comment1"] = "Blah" 

可以使用相同的获取值...

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

啊哈,就是差异。谢谢您的信息 – 2015-03-19 10:26:59

+1

无后顾之忧。当然,我可能会把它称为别的东西。使用名称“数组”的字典可能会令人困惑:-) – Fogmeister 2015-03-19 10:28:20

你有数组的第一个例子的概念,但对于第二个你需要一本字典,因为他们的键值对操作

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

的字典集合类型的快速参考可以found here