我试图把头放在Swift中初始化空数组。
对于字符串数组,这很简单:
var myStringArray: String[] = []
myStringArray += "a"
myStringArray += "b"
-> ["a", "b"]
和整数
var myIntArray: Int[] = []
myIntArray += 1
myIntArray += 2
-> [1, 2]
它也适用于其他类型的对象,例如NSImage对象:
let path = "/Library/Application Support/Apple/iChat Icons/Flags/"
let image1 = NSImage(byReferencingFile: path + "Brazil.png")
let image2 = NSImage(byReferencingFile: path + "Chile.png")
var myImageArray: NSImage[] = []
myImageArray += image1
myImageArray += image2
-> [<NSImage 0x7fe371c199f0 ...>, <NSImage 0x7fe371f39ea0 ...>]
但是,我无法计算出初始化空数组Dictionary的语法。
我知道您可以拥有一系列的Dictionary,因为使用初始值进行初始化是可行的:
let myDict1 = ["someKey":"someValue"]
let myDict2 = ["anotherKey":"anotherValue"]
var myDictArray = [myDict1]
myDictArray += myDict2
-> [["someKey": "someValue"], ["anotherKey": "anotherValue"]]
但是,这(您期望语法是这样)失败了:
var myNewDictArray: Dictionary[] = []
与错误 Cannot convert the expression's type 'Dictionary[]' to type 'Hashable'
所以问题是初始化字典项的空数组的正确方法是什么,为什么这种语法var myNewDictArray: Dictionary[] = []
不起作用?