Swift UnsafeMutableRawPointer 错误

Swift UnsafeMutableRawPointer Error

使用 Swift 3,我得到了这个,没有任何错误:

private var SessionRunningContext = 0

func addObservers() {
   self.session.addObserver(self, forKeyPath: "running", options: .new, context: &SessionRunningContext)
}

func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
   let newValue: AnyObject? = change![NSKeyValueChangeKey.newKey] as AnyObject?
   switch context! {
     case &SessionRunningContext:
         // Do something
   }
}

但是,当我在 iOS 12,Xcode Beta 上构建它时,我收到一条错误消息:

Use of extraneous '&'

对于这一行:

case &SessionRunningContext:

这似乎是 Xcode 10 beta 3 附带的 Swift 中的错误, 它已在 Xcode 10.0 beta 4 (10L213o) 中修复。

Xcode 10 beta 3 的可能解决方法是:

带有 where 子句的模式(归因于@Hamish):

switch context {
    case let x where x == &SessionRunningContext:
    // Do something

}

可选模式:

switch context {
    case .some(&SessionRunningContext):
    // Do something

}

一个简单的 if 语句:

if context == &SessionRunningContext {
     // Do something

}

另请注意,只有全局变量或静态地址 属性 提供适合用作上下文指针的持久指针,而不是 实例 属性,比较 Interacting with C Pointers 中的“指针参数转换的安全性”:

The pointer that results from these conversions is only guaranteed to be valid for the duration of a call. Even if you pass the same variable, array, or string as multiple pointer arguments, you could receive a different pointer each time. An exception to this is global or static stored variables. You can safely use the address of a global variable as a persistent unique pointer value, e.g.: as a KVO context parameter.