Swift: 扩展中的存储属性无法识别的选择器异常

Swift: Stored Properties in Extensions unrecognized selector exception

我有一个 NSURLSessionDownloadTask 的扩展,在这个扩展中,我使用 Objective C 关联对象创建了一个名为 'id' 的存储 属性。当我尝试设置 属性 时,我得到 'an unrecognized selector sent to instance'。下面是我的代码:

extension NSURLSessionDownloadTask {

  private struct AssociatedKeys {
    static var id: String?
  }

  var id: String? {
    get {
      return objc_getAssociatedObject(self, &AssociatedKeys.id) as? String
    }
    set {
      if let newValue = newValue {
        objc_setAssociatedObject(self, &AssociatedKeys.id, newValue as String?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
      }
    }
  }
}

稍后;

let task = session.downloadTaskWithURL(url)
task.id = identifier

我无法完全解释,但问题似乎是 session.downloadTaskWithURL(url) returns 一些实例 内部子类 __NSCFLocalDownloadTask.

如果您将扩展定义为 NSURLSessionTask 的扩展 而不是 NSURLSessionDownloadTask

extension NSURLSessionTask { ... }

然后它在我的测试中起作用了。