无法使用泛型分配此表达式的结果

时间:2015-04-07 10:26:08

标签: swift generics assign

我有以下通用类,我想管理字符串哈希:

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)" }
}

为什么编译器会在上面的赋值中出现问题?

1 个答案:

答案 0 :(得分:1)

init(name:String, set:[String:T]) {
    // ...
    set[key] = existingProfile // <-- error
    // ...
}

set指的是(immutable)方法参数。 请改用self.set来引用该属性。