Pix And Codes Pix And Codes - 3 months ago 7x
iOS Question

converting AnyObject to String in swift not working

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 {
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.


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

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