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

空扰寡人 提交于 2019-12-05 08:17:13
vacawama

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?

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