在 swift 中创建数组
Create an array in swift
我搜索了很多,但可能我看不懂结果。
我只发现 SWIFT 中的数组具有索引 int-values
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
我应该如何声明数组以及如何将值附加到该数组?
你的第一个例子是一个数组。你的第二个例子是字典。
对于使用键值对的字典...
myArray["Comment1"] = "Blah"
您使用相同的方法来获取值...
let value = myArray["Comment1"]
println(value)
你的第二个例子是字典
myArray["key"] = "value"
如果你想要字典数组,你必须像这样声明它
var myArray: [[String: String]]
您在第一个示例中了解了数组的概念,但对于第二个示例,您需要一个字典,因为它们对键值对进行操作
// 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
我搜索了很多,但可能我看不懂结果。
我只发现 SWIFT 中的数组具有索引 int-values
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
我应该如何声明数组以及如何将值附加到该数组?
你的第一个例子是一个数组。你的第二个例子是字典。
对于使用键值对的字典...
myArray["Comment1"] = "Blah"
您使用相同的方法来获取值...
let value = myArray["Comment1"]
println(value)
你的第二个例子是字典
myArray["key"] = "value"
如果你想要字典数组,你必须像这样声明它
var myArray: [[String: String]]
您在第一个示例中了解了数组的概念,但对于第二个示例,您需要一个字典,因为它们对键值对进行操作
// 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