Home > OS >  optional String array JSON
optional String array JSON

Time:07-10

I use the youtube API to get the ID of the video With the JSON function I add it to the array but when i put the video id from array i get me error

This is the code:

the struct:

// MARK: - Welcome
struct Welcome: Decodable {
    let items: [Item]
}

// MARK: - Item
struct Item: Decodable {
    let id: ID
}

// MARK: - ID
struct ID: Decodable {
    let videoId: String?
}

// MARK: - PageInfo
struct PageInfo: Decodable {
    let totalResults, resultsPerPage: Int
}

the code:

    var videos: Item?
@IBOutlet var playerView: YTPlayerView!

override func awakeFromNib() {
    super.awakeFromNib()
    playerView.delegate = self
    playerView.load(withVideoId: videos?.id.videoId) // HERE THE ERROR
    // Initialization code
    }

this error:

Option of the optional 'String?' The engraving should be turned off to a 'string' entry

CodePudding user response:

You need a String and not String? Try:

if let id = videos?.id.videoId {
    playerView.load(withVideoId: id) // HERE THE ERROR
    // Initialization code
    }
}

Reason: As your videos and id vars are Optionals (? at the end) you need to check if it is not nil befor accessing it.

CodePudding user response:

Question Mark in Kotlin :

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references) by using the question mark (?).

Remove String? and replace it String for your code

This is the code: the struct :

// MARK: - Welcome
struct Welcome: Decodable {
    let items: [Item]
}

// MARK: - Item
struct Item: Decodable {
    let id: ID
}

// MARK: - ID
struct ID: Decodable {
    let videoId: String?
}

// MARK: - PageInfo
struct PageInfo: Decodable {
    let totalResults, resultsPerPage: Int
}

the code :

    var videos: Item?
@IBOutlet var playerView: YTPlayerView!

override func awakeFromNib() {
    super.awakeFromNib()
    playerView.delegate = self
    playerView.load(withVideoId: videos?.id.videoId) // HERE THE ERROR
    // Initialization code
    }
  • Related