【问题标题】:AVPlayer cannot assign value of type to typeAVPlayer 无法将类型的值分配给类型
【发布时间】:2017-01-22 14:36:13
【问题描述】:

我最近将我的代码升级到了 swift 3,我有 2 个与我的应用中的 AVPlayer 相关的错误。

编辑:这里是声明:

public var avPlayer = AVPlayer()
public var avPlayerItem = AVPlayerItem?.self

这是我引用的函数:

func stream() {
    let urlString = streamURLForSong
    let urlItem = URL(string: urlString)
    avPlayerItem = AVPlayerItem(url: urlItem!) // ERROR: Cannot assign value of type 'AVPlayerItem' to type 'AVPlayerItem?.Type?'
    avPlayer = AVPlayer(playerItem: avPlayerItem!) // ERROR: Cannot convert value of type 'AVPlayerItem?.Type' (aka 'Optional<AVPlayerItem>.Type') to expected argument 'AVPlayerItem?'
}

这之前有效,但在使用 Xcode 升级到 Swift 3 后,显示了上面注释的错误。

我该如何解决这个问题?

提前致谢!

【问题讨论】:

  • 我们可以看看你的avPlayerItem声明吗?
  • 请出示avPlayerItemavPlayer声明。
  • public var avPlayer = AVPlayer() public var avPlayerItem = AVPlayerItem?.self
  • “这在以前有效”不,它从来没有。说avPlayerItem = AVPlayerItem?.self从不正确的。

标签: ios swift3 avplayer avplayeritem


【解决方案1】:

这段代码是错误的:

public var avPlayerItem = AVPlayerItem?.self

删除.self。该代码使它成为一个 type 而你想要一个 instance 去这里。现在删除= 并改用: 来声明类型。

举个简单的例子,这段代码是非法的:

var x = String?.self
x = "howdy" // compile error

这是需要的:

var x : String?
x = "howdy"

【讨论】:

    【解决方案2】:

    我能够在 Xcode 操场上稍作修改就可以编译这个函数。我的版本是这样的:

    import AVFoundation
    
    func stream() {  
        let urlString = "http://google.com"
        let urlItem = URL(string: urlString)
        let avPlayerItem: AVPlayerItem? = AVPlayerItem(url: urlItem!) // ERROR: Cannot assign value of type 'AVPlayerItem' to type 'AVPlayerItem?.Type?'
        let avPlayer = AVPlayer(playerItem: avPlayerItem) // ERROR: Cannot convert value of type 'AVPlayerItem?.Type' (aka 'Optional<AVPlayerItem>.Type') to expected argument 'AVPlayerItem?'
    }
    

    我将 urlString 设置为一个虚拟地址,并更改了最后一行,以便我们在将 AVPlayerItem 传递给 AVPlayer 时不会强制打开它。

    编辑:

    如果你想告诉 Swift 为 avPlayerItem 使用什么数据类型,你想使用这个语法:

    public var avPlayerItem: AVPlayerItem
    

    您所做的是将类本身分配为avPlayerItem 变量的内容,因此数据类型实际上是AVPlayerItem?.Type? 而不是AVPlayerItem?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 2019-12-03
      • 2017-08-07
      • 2021-03-08
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多