【问题标题】:"Initializer for conditional binding must have Optional type, not '[String]'"“条件绑定的初始化程序必须具有可选类型,而不是 '[String]'”
【发布时间】:2017-01-22 00:22:13
【问题描述】:

我正在尝试为在 Swift 3.0 中工作的 CocoaPods 获取 pod“Swift-YouTube-Player”,但我收到以下代码的以下错误(错误指向 let pathComponents 部分)。

"条件绑定的初始化器必须是 Optional 类型,而不是 '[String]'"

public func videoIDFromYouTubeURL(_ videoURL: URL) -> String? {
    if let host = videoURL.host, let pathComponents = videoURL.pathComponents , pathComponents.count > 1 && host.hasSuffix("youtu.be") {
        return pathComponents[1]
    }
    return videoURL.queryStringComponents()["v"] as? String
}

【问题讨论】:

    标签: ios swift youtube cocoapods swift3


    【解决方案1】:

    看起来videoURL.pathComponents 不是可选的,所以你必须像这样分解条件:

    public func videoIDFromYouTubeURL(_ videoURL: URL) -> String? {
        if let host = videoURL.host {
            let pathComponents = videoURL.pathComponents 
            if pathComponents.count > 1 && host.hasSuffix("youtu.be") {
                return pathComponents[1]
            }
        } 
        return videoURL.queryStringComponents()["v"] as? String
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2018-03-25
      • 2016-01-08
      • 2017-04-08
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多