我试图编写一些Swift代码,用于在字典中存储集合集合(因此可以很容易地将其序列化为plist)。在Objective-C中足够简单,但我在Swift中看到了一些我不明白的行为。
可玩的示例:
import Cocoa
typealias StringMap=Dictionary<String, String>
var collections = Dictionary<String, Array<StringMap>>();
// Add an empty "books" collection
collections["books"] = Array<StringMap>();
// Look up the books collection
var books = collections["books"] as Array<StringMap>!;
// Add an item to it
var book = ["name": "The Complete Peanuts", "author": "Charles M. Schulz"]
books.append(book);
// This is now 1
books.count
// Look up the books collection again
books = collections["books"] as Array<StringMap>!;
// This is zero
books.count
似乎从字典中检索books数组是获取数组的副本,而不是对它的引用。我想要一个参考,所以我可以更新它。
答案 0 :(得分:1)
在Swift中,Array
和Dictionary
为struct
,即value type。将其分配给另一个变量或常量时,将复制它。例如:
var a:[Int] = []
var b = a
b.append(42)
// a -> []
// b -> [42]
因此,在您的情况下,您应该从collections
变量:
typealias StringMap=Dictionary<String, String>
var collections = Dictionary<String, Array<StringMap>>();
collections["books"] = Array<StringMap>();
var book = ["name": "The Complete Peanuts", "author": "Charles M. Schulz"]
collections["books"]!.append(book)
collections["books"]!.count
或者,准备数组,并分配到字典:
var collections = Dictionary<String, Array<StringMap>>();
var books = Array<StringMap>();
var book = ["name": "The Complete Peanuts", "author": "Charles M. Schulz"]
books.append(book)
collections["books"] = books