swift - 如何正确使用词典收藏?

标签 swift dictionary

这是我的代码:

class className: Codable {
    let comments: [String: String, String:String]
}

我收到以下错误:

Expected ']' in dictionary type

Expected declaration

Consecutive declarations on a line muse be separated by ';'

来自 Swift docs它是这样做的(我认为):

let comments: [String: String]

但对我来说它不起作用,因为我在 mongoose.Schema 中的 comments 定义如下(在服务器中):

comments: [{
    identifier: String,
    text: String
}]

我定义了评论集合以将其推送到服务器进行测试,如下所示(有效):

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"]

现在我的问题是,如何在扩展 Codable 的类中定义 comments 以匹配我在服务器中的 comments

最佳答案

let comments: [String: String]才是正确的做法。

你想要一个字典,它的键是String s,其值也是 String s,这就是上面一行声明的内容。

如果您检查 comments 的类型当用初始值声明它时变量(选项单击变量名称),你会看到它的类型是 [String:String] , 这只是 Dictionary<String,String> 的简写符号.

var comments = ["identifier" : "SomeRandomText", "text": "SomeRandomText"] //Here comments is of type [String:String]

关于swift - 如何正确使用词典收藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634238/

相关文章:

python - 在字典中过滤日期 - python

macos - 如何防止 Storyboard 打开窗口

swift - 从 appdelegate 更新 viewcontroller - 最佳实践?

python - 如何将一个字符串分成3组,然后相应地打印到组中?

Python 函数 - 循环字典并更新值

python - 如何使用 max() 函数找到字典中最大值对应的键?

ios - Crashlytics 日志中没有自动跟踪的屏幕。只有自定义事件可见

ios - 如何知道附加函数是否正在填充 NSObject 的属性

xcode - GCDAsyncSocket重新启动readDataToData内存增加

python - 将 JSON 加载到 multiprocessing.managers.DictProxy 对象中