How do I convert an object of type (NSObject, AnyObject)
to the type String
?
At the end of the first line of the method below, as String
causes the compiler error:
'(NSObject, AnyObject)' is not convertible to 'String'
Casting street
to NSString
instead of String
compiles, but I'm casting street
to String
because I want to compare it to placemark.name
, which has the type String!
, not NSString
.
I know name
and street
are optionals, but I'm assuming they're not nil
for now because all the places returned from MKLocalSearch
seem to have non-nil names and streets.
func formatPlacemark(placemark: CLPlacemark) -> (String, String) {
let street = placemark.addressDictionary["Street"] as String
if placemark.name == street {
// Do something
}
}
A String
is not an object, so you do need to cast it to an NSString
. I would recommend the following syntax to cast it and unwrap it at the same time. Don't worry about comparing it to a variable of type String!
since they are compatible. This will work:
func formatPlacemark(placemark: CLPlacemark) -> (String, String) {
if let street = placemark.addressDictionary["Street"] as? NSString {
if placemark.name == street {
// Do something
}
}
}
This has the added benefits that if "Street" is not a valid key in your dictionary or if the object type is something other than NSString
, this will not crash. It just won't enter the block.
If you really want street to be a String
you could do this:
if let street:String = placemark.addressDictionary["Street"] as? NSString
but it doesn't buy you anything in this case.
The return type from looking up via subscript for a swift dictionary has to be an optional since there may be no value for the given key.
Therefor you must do:
as String?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With