1
votes

I make POST request to the server from my app, and I get jsonString as the response. I have made function to convert string to dictionary which looks like this:

    func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

after getting the response from the server I convert the string to dictionary by function and then I want to check if user is logged in:

       let result = convertStringToDictionary(jsonString as String)

        if (result!["loggedIn"] == "1")
        {
            print("You are logged in!")
        }

And then I get the error "Cannot convert value of type AnyObject? to expected argument String". I suppose I have to convert variable of type AnyObject to String if i want to compare it to string. I have tried every option which I have found on the Google but I havent got it to work.

2

2 Answers

1
votes

Because result is a dictionary of type [String : AnyObject], the values you extract from it will be typed as AnyObject?, which has no valid operator overload for == with a String. You need to cast the extracted value to a String before you can compare it to "1".

What you probably want is something like:

if let result = convertStringToDictionary(jsonString as String), 
    loggedIn = result["loggedIn"] as? String 
    where loggedIn == "1" {
    print("You are logged in")
}

Note that if your JSON has the "loggedIn" field as an Integer, like:

{
    "loggedIn" : 1
}

You would want to cast loggedIn as Integer, not String.

0
votes

You have to tell the compiler that the expected type is a String

if let loggedIn = result?["loggedIn"] as? String where loggedIn == "1" { ...