if let doesn't unwrap optional value for MKAnnotation's title property
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)
}
}
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 }
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??
.
Can you safely unwrap nested optionals in swift in one line?
You could do it like so:
if let title = view.annotation?.title as? String {
}
view.annotation?.title
is a double optional string: String??
since both the property annotation
of an MKAnnotationView
, and its own property title
, are optional.
You could also use the guard statement like so:
guard let title = view.annotation?.title as? String else {
return
}
//use title in the rest of the scope
you could also use a switch
statement :
switch title {
case .some(.some(let t)):
//use the title here
print(t)
default:
break
}
Related Topics
Error After Importing Swift into Objective-C
How to Convert Duration Form Youtube API in Swift
How to Design an Uiscrollview in Storyboard
Writing JSON File Programmatically Swift
How to Insert a Override Function into a If Else Statement
Swift Converting Signed Array of Int [Int8] to Unsigned Array of Int [Uint8]
Center Horizontal Uicollectionview Based on Content
How to Update Individual Array Element in Firebase with iOS Swift
Target Is Not Found, Please Reconnect the Device, Xcode:Device Support File
How to Set Response Data into Todayextenstion Widget
Checking If Text Fields Are Empty Cause Error in Swift 2
Mysterious "Cryptographic Verification Failure" Error on MACos Sierra, Xcode 8