'(NSObject, AnyObject)' does not convert to 'String'

How to convert an object of type (NSObject, AnyObject) to type String ?

At the end of the first line of the method below, as String raises a compiler error:

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

Drop street in NSString instead of String compilation, but I drop street in String because I want to compare it with placemark.name , which is of type String! , not NSString .

I know that name and street are options, but I assume that they are not nil , because all the places returned from MKLocalSearch seem to have names and streets other than zero.

 func formatPlacemark(placemark: CLPlacemark) -> (String, String) { let street = placemark.addressDictionary["Street"] as String if placemark.name == street { // Do something } } 
+6
source share
3 answers

A String not an object, so you need to send it to NSString . I would recommend the following syntax for creating and deploying it at the same time. Don't worry about comparing it to a variable of type String! because 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 additional advantages: if "Street" is not a valid key in your dictionary, or if the type of the object is something other than NSString , it will not crash. He just won't go into the block.

If you really want the street to be String , you could do this:

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

but in this case he won’t buy anything.

+6
source

The return index search type for the quick dictionary should be optional, since there may be no value for this key.

To do this, you must:

 as String? 
+2
source

I think this could be due to addressDictionary as an NSDictionary .

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

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

Source: https://habr.com/ru/post/974575/


All Articles