gpt4 book ai didi

ios - Swift UnsafeMutableRawPointer 错误

转载 作者:可可西里 更新时间:2023-11-01 00:55:09 27 4
gpt4 key购买 nike

使用 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.

关于ios - Swift UnsafeMutableRawPointer 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51427842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com