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

落花浮王杯 提交于 2020-01-13 09:31:52

问题


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
    }
}

回答1:


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.




回答2:


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?



回答3:


I think it may have to do with addressDictionary being an NSDictionary.

If you convert addressDictionary to a Swift dictionary, it should work.

let street = (placemark.addressDictionary as Dictionary<String, String>)["String"]


来源:https://stackoverflow.com/questions/25579183/nsobject-anyobject-is-not-convertible-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!