Fattaneh Talebi
Fattaneh Talebi

Reputation: 767

How to convert variable of type Any object to String when this variable contains Null in iOS?

The problem is when I want to cast user variable to string, it says unable to read data. It might be because the user object contains null.

Response:

SUCCESS: {
    data =     {
        user =         {
            email = "<null>";
            firstName = "<null>";
        };

        //... 
    };
    message = "";
    messageCode = "API_200";
} 

Code:

if let responseDict = response["data"] as? [String : AnyObject] {

    if let user = responseDict["user"] {
       if let userString = user as? String
       {
          var itIsExtracted = true;
       }
    }
}

Upvotes: 1

Views: 62

Answers (1)

Jacob Jidell
Jacob Jidell

Reputation: 2792

What I can see is that your user-object is declared as an Any. Try to set it as a dictionary.

guard let responseDict = response["data"] as? [String : Any],
    let user = responseDict["user"] as? [String : Any] else {
        // There is no user
        return
}

if let userEmail = user["email"] as? String {
    print(userEmail)
    // Can be a result as "<null>" because of server result
}
if let firstName = user["firstName"] as? String {
    print(firstName)
    // Can be a result as "<null>" because of server result
}

I can also add what @Vadian said. Blame the owner of the website to send real null values, not a stringified null.

Upvotes: 2

Related Questions