I just want to extract some string values from a json response in Swift but I just can't find a simple way to do it.
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 is the correct way ?
cheers
This answer was last revised for Swift 5.4 and Xcode 12.5.
In Swift, String
is a struct, not a class. You need to use Any
, not AnyObject
.
let result: [String: Any] = ["name" : "Steve", "surname" : "Jobs"]
Casting should be done optionally, using as?
instead of as
.
if let name = result["name"] as? String {
// no error
}
Try SwiftyJSON which is a better way to deal with 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"])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With