gpt4 book ai didi

Swift 4 切换到新的观察 API

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:08 25 4
gpt4 key购买 nike

我在使用 Swift 4 中新的 observe 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) {

}
}

但是我得到一个错误

Type of expression is ambiguous without more context.

我该如何解决?不确定 keyPath 语法。

在上面的闭包中提取AVPlayerStatus也有警告

Cast from 'NSKeyValueObservedChange' to unrelated type 'NSNumber' always fails"

最佳答案

currentItemAVPlayer 的一个可选属性。下面编译在 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’s ‘observe()’ doesn’t work for key paths with optionals?在 Swift 论坛中。

关于Swift 4 切换到新的观察 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475491/

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