Extract string values from dictionary <String, AnyObject> in Swift
I just want to extract some string values from a json response in Swift, but I just can't seem to find an easy way to do this.
var result: Dictionary<String, AnyObject> = [ "name" : "Steve", "surname" : "Jobs"]
if let name = result["name"] {
//Warning: Constant 'name' inferred to have 'AnyObject', which may be unexpected
}
if let name = result["name"] as String {
//Error: (String, AnyObject) is not convertible to String
}
What's the right way?
amuses
source to share
In Swift String
, it is a struct, not a class. The protocol you need to use is Any
, not AnyObject
. Alternatively, you can import Foundation
also downcast AnyObject as? NSString
.
When talking about downcasting, you can optionally do so using the operator ?
. Your final code should look like this:
let result : [String: Any] = ["name" : "Steve", "surname" : "Jobs"]
if let name = result["name"] as? String {
// no error
}
PS You can use the new annotation [KeyType: ValueType]
instead Dictionary<KeyType, ValueType>
.
source to share
Try SwiftyJSON which is the best way to handle JSON data in Swift
var result: Dictionary<String, AnyObject> = [ "name" : "Steve", "surname" : "Jobs"]
let json = SwiftJSON.JSON(object: result)
if let name = json["name"].string {
//do what you want
} else {
//print the error message if you like
println(json["name"])
}
source to share