【问题标题】:How do I update Swift Dictionary values of mixed types, in particular Arrays如何更新混合类型的 Swift 字典值,特别是数组
【发布时间】:2019-01-13 22:24:53
【问题描述】:

我有一个混合类型(字符串、NSImage 和数组)的字典。附加到数组时,出现错误“'Any??' 类型的值没有成员'追加'”。我看不到如何将“file_list”值转换为数组,因此我可以将值附加到它。

            var dataDict: [String:Any?] = [
                "data_id" : someString,
                "thumbnail" : nil,
                "file_list" : [],
            ]
            // do stuff... find files... whirrr wizzzz
            dataDict["thumbnail"] = NSImage(byReferencingFile: someFile)
            dataDict["file_list"].append( someFile ) <- ERROR: Value of type 'Any??' has no member 'append'

【问题讨论】:

  • 你为什么不使用像struct DataDict {var dataId: String; var thumbname: NSImage?; var fileList: [String]}这样的结构?

标签: swift dictionary types


【解决方案1】:

你不能。您需要首先获取您的键值,从Any 转换为[String],附加新值,然后将修改后的数组值分配给您的键:

if var array = dataDict["file_list"] as? [String] {
    array.append(someFile)
    dataDict["file_list"] = array
}

if let array =  dataDict["file_list"] as? [String] {
    dataDict["file_list"] = array + [someFile]
}

另一种选择是按照 OOPer 在 cmets 中的建议创建自定义结构

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2020-10-06
    • 2015-08-13
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多