我收到一個錯誤:“有嗎?” 不能轉換為“組態檔”我不知道如何更正。我正在嘗試擴展字典。我需要 Profile Struct 中顯示的結構
struct Profiles {
var id: Int
var name: String
}
extension NSDictionary {
var profileDictionary: [String : Profiles] {
var dictionary: [String : Profiles] = [:]
let keys = self.allKeys.compactMap { $0 as? String }
for key in keys {
let keyValue = self.value(forKey: key) as Profiles
dictionary[key] = keyValue
}
return dictionary
}
}
uj5u.com熱心網友回復:
不確定為什么在使用NSDictionary
Swift 編碼時需要使用。我將發布 Dictionary 方法,但NSDictionary
完全相同。您可以使用 reduce 方法并將所有鍵值對轉換為(String, Profiles)
并將其添加到結果字典中:
extension Dictionary {
var profileDictionary: [String : Profiles] {
reduce(into: [:], { result, keyValue in
if let kv = keyValue as? (String, Profiles) {
result[kv.0] = kv.1
}
})
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516576.html
標籤:迅速