Swift 4切换到新的观察API [英] Swift 4 switch to new observe API

查看:107
本文介绍了Swift 4切换到新的观察API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift 4中使用新的observe API遇到了麻烦.

I am having trouble with the new observe API in Swift 4.

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语法.

How do I fix it? Not sure about keyPath syntax.

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

There is also a warning in extracting AVPlayerStatus in the closure above

从"NSKeyValueObservedChange"到不相关类型"NSNumber"的广播始终失败"

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

推荐答案

currentItemAVPlayer可选属性.以下编译 在Swift 4.2/Xcode 10中(请注意关键路径中的附加问号):

currentItem is an optional property of AVPlayer. The following compiles in Swift 4.2/Xcode 10 (note the additional question mark in the key path):

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`
    }
}

observed属性是可选的AVPlayer.Status?,因此 回调内的change.newValue是双精度可选" AVPlayer.Status??,必须解开两次.

The observed property is an optional AVPlayer.Status?, therefore change.newValue inside the callback is a "double optional" AVPlayer.Status?? and must be unwrapped twice.

相比之下,它可能无法在较早的Swift版本中编译 Swift的'observe()'不

It may fail to compile in older Swift versions, compare Swift’s ‘observe()’ doesn’t work for key paths with optionals? in the Swift forum.

这篇关于Swift 4切换到新的观察API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆