在Swift中初始化空字典数组

时间:2014-06-09 01:33:49

标签: arrays dictionary swift

我正试图在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[] = []不起作用?

6 个答案:

答案 0 :(得分:188)

您需要为字典提供类型:

var myNewDictArray: [Dictionary<String, Int>] = []

var myNewDictArray = [Dictionary<String, Int>]()

修改:您还可以使用较短的语法:

var myNewDictArray: [[String:Int]] = []

var myNewDictArray = [[String:Int]]()

答案 1 :(得分:9)

这将创建一个空的,不可变的字典:

let dictionary = [ : ]

如果你想要一个可变的:

var dictionary = [ : ]

这两个词典都默认为Dictionary<String?, AnyObject?>

答案 2 :(得分:5)

这不起作用的原因:

var myNewDictArray: Dictionary[] = []

是您在定义字典时需要为字典的键和值提供类型。这些行中的每一行都将创建一个包含字符串键和字符串值的空字典数组:

var dictArray1: Dictionary<String, String>[] = Dictionary<String, String>[]()
var dictArray2: Dictionary<String, String>[] = []
var dictArray3 = Dictionary<String, String>[]()

答案 3 :(得分:0)

您无法再使用元素连接。

class Image {}
Image i1
Image i2

var x = [Image]()

x += i1 // will not work (adding an element is ambiguous)
x += [i1] // this will work (concatenate an array to an array with the same elements)

x += [i1, i2] // also good

答案 4 :(得分:0)

var yourArrayname = [String]() // String or anyOther according to need

答案 5 :(得分:-1)

如果你想使用swift 2.3,你可以使用它!

let path = "/Library/Application Support/Apple/iChat Icons/Flags/"
let image1 = UIImage(contentsOfFile: readPath + "Brazil.png")
let image2 = UIImage(contentsOfFile: readPath + "Chile.png")

var myImageArray = [UIImage]()
myImageArray.append(image1)
myImageArray.append(image2)