I am getting an error: 'Any?' is not convertible to 'Profiles' I am not sure how to correct. I am trying to extend the dictionary. I am needing the structure show in the 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
}
}
CodePudding user response:
Not sure why you need to use NSDictionary
when coding with Swift. I will post the Dictionary approach but NSDictionary
would be exactly the same. You can use reduce method and convert all key value pairs to (String, Profiles)
and add it to the resulting dictionary:
extension Dictionary {
var profileDictionary: [String : Profiles] {
reduce(into: [:], { result, keyValue in
if let kv = keyValue as? (String, Profiles) {
result[kv.0] = kv.1
}
})
}
}