'(NSObject,AnyObject)'不能转换为'String' [英] '(NSObject, AnyObject)' is not convertible to 'String'

查看:257
本文介绍了'(NSObject,AnyObject)'不能转换为'String'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将类型为(NSObject,AnyObject)的对象转换为类型 String



在下面方法的第一行结尾处, as String 导致编译器错误:

 '(NSObject,AnyObject)'不能转换为'String'

Casting street to NSString 而不是 String 编译,但是我正在将 street 转换为 String ,因为我想将其与 placemark.name ,其类型为 String!,而不是 NSString



我知道名称 street 可选项,但是我假设现在不是 nil ,因为从 MKLocalSearch 返回的所有地方似乎都有非零名称和街道。

  func formatPlacemark(地标:CLPlacemark) - > (String,String){
let street = placemark.addressDictionary [Street] as String
if placemark.name == street {
// do something
}
}


解决方案

A String 不是一个对象,所以您需要将其转换为 NSString 。我会推荐以下语法来转换它并在同一时间展开它。不要担心与 String!类型的变量进行比较,因为它们是兼容的。这将工作:

  func formatPlacemark(地标:CLPlacemark) - > (String,String){
if let street = placemark.addressDictionary [Street] as? NSString {
if placemark.name == street {
// do something
}
}
}

如果街不是字典中的有效键,或者对象类型不是 NSString之外的其他好处,这不会崩溃。



如果您真的想要街道成为 String 你可以这样做:

  if let street:String = placemark.addressDictionary [Street] as? 






但是在这种情况下,您不会向您收取任何费用。

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.

这篇关于'(NSObject,AnyObject)'不能转换为'String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆