在swift中将字典添加到字典中

A.A*_*omi 1 dictionary ios swift

根据这个页面,可以将一个完整的字典添加到另一个 http://code.tutsplus.com/tutorials/an-introduction-to-swift-part-1--cms-21389

但运行代码给了我编译错误

var dictionary = ["cat": 2,"dog":4,"snake":8]; // mutable dictionary
dictionary["lion"] = 7; // add element to dictionary
dictionary += ["bear":1,"mouse":6]; // add dictionary to dictionary
Run Code Online (Sandbox Code Playgroud)

错误:

[string: Int] is not identical to UInt8
Run Code Online (Sandbox Code Playgroud)

是否有正确的方法在swift中执行此功能?我应该逐一添加它们?

Jar*_*sen 6

您引用的页面是错误的,+=不是字典的有效运算符,尽管它适用于数组.如果您想查看所有已定义的+=操作符,可以import Swift在操场顶部写入并按住+单击Swift,然后搜索+=.这将带您进入定义所有主要Swift类型和函数的文件.

您链接到的页面还包含一些有关快速浏览数组部分的其他错误信息,其中表示您可以执行此操作:array += "four".所以,不要太信任这个页面.我相信你以前能够将这样的元素附加到早期版本的Swift中的数组中,但它已被更改.

好消息是,使用Swift,您可以定义自己的自定义运算符!以下是快速实现,应该做你想要的.

func +=<U,T>(inout lhs: [U:T], rhs: [U:T]) {
    for (key, value) in rhs {
        lhs[key] = value
    }
}
Run Code Online (Sandbox Code Playgroud)