Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract String values from Dictionary<String, AnyObject> in Swift

Tags:

swift

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

like image 838
Jan Avatar asked Dec 04 '22 05:12

Jan


2 Answers

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
}
like image 197
akashivskyy Avatar answered May 30 '23 16:05

akashivskyy


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"])
}
like image 26
tangplin Avatar answered May 30 '23 15:05

tangplin