简体   繁体   中英

AVPlayer cannot assign value of type to type

I recently upgraded my code to swift 3, and I have 2 errors that relate to the AVPlayer in my app.

EDIT: Here are the declarations:

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

Here's the function I'm referencing:

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?'
}

This worked before, but after upgrading to Swift 3 using Xcode, the errors commented above are shown.

How do I fix this?

Thanks in advance!

I was able to get this function to compile with slight modification in an Xcode playground. My version looked like this:

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?'
}

I made urlString a dummy address, and also changed the last line so that we don't force unwrap your AVPlayerItem when passing it to AVPlayer .

Edit:

If you're trying to tell Swift what data type to use for avPlayerItem , you want to use this syntax:

public var avPlayerItem: AVPlayerItem

What you've done is assign the class itself as the contents of the avPlayerItem variable, so the data type is actually AVPlayerItem?.Type? instead of AVPlayerItem? .

This code is wrong:

public var avPlayerItem = AVPlayerItem?.self

Delete .self . That code makes this a type whereas you want an instance to go here. Now delete = and use : instead, to declare the type.

To give a simpler example, this code is illegal:

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

This is what is needed:

var x : String?
x = "howdy"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM