如何更新混合类型的 Swift 字典值,尤其是数组



我有一个混合类型的字典(字符串,NSImage和一个数组(。追加到数组时,我收到错误"类型'任何??'的值没有成员'追加'"。我不明白如何将"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'

你不能。您需要首先获取从 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 注释中的建议创建自定义结构

最新更新