Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'(NSObject, AnyObject)' is not convertible to 'String'

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
    }
}
like image 575
ma11hew28 Avatar asked Aug 30 '14 05:08

ma11hew28


Video Answer


2 Answers

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.

like image 182
vacawama Avatar answered Sep 16 '22 12:09

vacawama


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?
like image 44
Mike Pollard Avatar answered Sep 20 '22 12:09

Mike Pollard