无法使用泛型分配给此表达式的结果
Cannot assign to the result of this expression with generics
我有以下通用 class,我想在其中管理字符串哈希:
class NamedProfile<T> {
private var set = [String:T]()
private var profiles = [String]()
private let userDefaults = NSUserDefaults.standardUserDefaults()
private let profileName:String
var currentSet = ""
init(name:String, set:[String:T]) {
profileName = name
self.set = set
if let existingProfiles = userDefaults.objectForKey(name) as? [String] {
profiles = existingProfiles
}
for key in profiles {
if let existingProfile = userDefaults.objectForKey(profileNamed(name)) as? T {
set[key] = existingProfile // <-- error
}
}
}
private func profileNamed(name:String) -> String { return "\(profileName) \(name)" }
}
为什么编译器会在上面的赋值中出错?
在
init(name:String, set:[String:T]) {
// ...
set[key] = existingProfile // <-- error
// ...
}
set
指的是(不可变的)方法参数。
使用 self.set
代替 属性.
我有以下通用 class,我想在其中管理字符串哈希:
class NamedProfile<T> {
private var set = [String:T]()
private var profiles = [String]()
private let userDefaults = NSUserDefaults.standardUserDefaults()
private let profileName:String
var currentSet = ""
init(name:String, set:[String:T]) {
profileName = name
self.set = set
if let existingProfiles = userDefaults.objectForKey(name) as? [String] {
profiles = existingProfiles
}
for key in profiles {
if let existingProfile = userDefaults.objectForKey(profileNamed(name)) as? T {
set[key] = existingProfile // <-- error
}
}
}
private func profileNamed(name:String) -> String { return "\(profileName) \(name)" }
}
为什么编译器会在上面的赋值中出错?
在
init(name:String, set:[String:T]) {
// ...
set[key] = existingProfile // <-- error
// ...
}
set
指的是(不可变的)方法参数。
使用 self.set
代替 属性.