【问题标题】:Compile error with optional binding使用可选绑定编译错误
【发布时间】:2015-11-05 14:04:47
【问题描述】:

使用 Xcode 7 beta 5,以下代码:

public func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
    guard let title: String = annotation.title else // compile error
    {
        return nil
    }

    ...

...编译时出现错误“Value of optional type 'String?'没有打开;你是不是要使用“!”或'?'?“。 MKAnnotation 是一个带有可选字符串的协议:

public protocol MKAnnotation : NSObjectProtocol {

    ...
    optional public var title: String? { get }
    ...
}

这可能很明显,但我看不出有什么问题。你有看到? 谢谢。

编辑:我不相信它是“Value of optional type String? not unwrapped”的副本,因为在后一种情况下没有暂定的可选绑定。

【问题讨论】:

  • 奇怪。你可以使用可选绑定而不是保护语句并让它工作吗?
  • 我在使用保护之前使用了带有“if let”的可选绑定,同样的问题。

标签: swift


【解决方案1】:

我可能已经找到了答案:“可选”和“?”似乎使要绑定的类型相当于一个双可选字符串,即:“String??”。下面的代码编译得很好:

    guard let titleStillOptional = annotation.title, let title = titleStillOptional else
    {
        return nil
    }

【讨论】:

    【解决方案2】:

    你没有在guard中设置类型,只需使用:

    guard let title = annotation.title else {
        return nil
    }
    

    【讨论】:

    • 我的初始代码没有类型,但标题类型被推断为字符串?并强迫我把标题!无处不在。
    • 它似乎工作,但它只绑定第一个可选,而不是第二个。如果要将代码中的标题用作字符串,则需要使用 ! 强制展开。你同意吗?
    • 是的,调查了一下,好像是这样。如果你解开 annotation.titlereturns 可选,那么你需要再次解开。 annotation.titleString?? 类型,对我来说似乎有点不对劲。
    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多