如果let不解开MKAnnotation的title属性的可选值 [英] if let doesn't unwrap optional value for MKAnnotation's title property
问题描述
我想用if-let语句解开可选值. 我需要获得MKAnnotation的标题.
I want to unwrap optional value with if-let statement. I need to get title of MKAnnotation.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let title = view.annotation?.title {
print(title) //Optional("Moscow")
}
}
为什么if-let在这里不起作用?
Why if-let doesn't work here?
推荐答案
MKAnnotation.title
的类型为String??
,它是嵌套的Optional
,因此您需要可选地将其绑定两次.
The type of MKAnnotation.title
is String??
, it's a nested Optional
, so you need to optional bind it twice.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let optionalTitle = view.annotation?.title, let title = optionalTitle {
print(title)
}
}
即使根据 MKAnnotation.title 的文档,标题的类型应为String?
,因为title
被声明为不需要的协议属性:
Even though according to the documentation of MKAnnotation.title, the type of title should be String?
, since title
is declared as a non-required protocol property:
optional var title: String? { get }
通过MKAnnotation
协议类型而不是通过实现协议的具体类型访问
时,它将被包裹在另一个Optional
中,这表示title
属性甚至可能无法通过具体类型实现来实现协议.因此,当访问MKAnnotation
对象的title
属性而不是具体类型符合MKAnnotation
的对象时,title
的类型将为String??
.
when accessed through the MKAnnotation
protocol type rather than the concrete type implementing the protocol, it becomes wrapped in another Optional
, which represents the fact that the title
property might not even be implemented by the concrete type implementing the protocol. Hence, when accessing the title
property of an MKAnnotation
object rather than an object with a concrete type conforming to MKAnnotation
, the type of title
will be String??
.
这篇关于如果let不解开MKAnnotation的title属性的可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!