我observe
在Swift 4中遇到了新API的麻烦。
player = AVPlayer()
player?.observe(\.currentItem.status, options: [.new], changeHandler: { [weak self] (player, newValue) in
if let status = AVPlayer.Status(rawValue: (newValue as! NSNumber).intValue) {
}
}
但我得到一个错误
没有更多上下文的情况下,表达类型不明确。
我如何解决它?不确定keyPath
语法。
在上面的关闭中提取AVPlayerStatus时也有警告
从“ NSKeyValueObservedChange”强制转换为不相关的类型“ NSNumber”始终失败”
currentItem
是的可选属性AVPlayer
。以下在Swift 4.2 / Xcode 10中进行编译(请注意关键路径中的其他问号):
let observer = player.observe(\.currentItem?.status, options: [.new]) {
(player, change) in
guard let optStatus = change.newValue else {
return // No new value provided by observer
}
if let status = optStatus {
// `status` is the new status, type is `AVPlayerItem.Status`
} else {
// New status is `nil`
}
}
观察到的属性是可选的AVPlayer.Status?
,因此change.newValue
在回调内部是“双重可选”的AVPlayer.Status??
,必须解开两次。
它可能无法在较早的Swift版本中编译,比较Swift的'observe()'是否不适用于带有可选键的关键路径?在Swift论坛中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句