【发布时间】:2014-07-29 13:00:06
【问题描述】:
我正试图在 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 ...>]
但是我无法确定初始化空字典数组的语法。
我知道您可以拥有一个字典数组,因为使用初始值进行初始化是可行的:
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[] = [] 不起作用?
【问题讨论】:
标签: arrays dictionary swift