swift2optional-values

can't remove optional() from string after updating to latest xcode?


after updating xcode I simply can't remove the optional() from my string?

retrievedUsername = KeychainWrapper.stringForKey("username")!

this prints out

optional("HK")

but I need it to be

HK

I've tried

if let username = KeychainWrapper.stringForKey("username"){
   retrievedUsername = username
}

but no luck! any ideas?


Solution

  • Your value is probably an optional containing an optional, so you'll have to unwrap it twice:

    if let temp = KeychainWrapper.stringForKey("username"), let username = temp {
        retrievedUsername = username
    }
    

    If this doesn't work, this is because it's not a double optional, and it means that your original string already contains the text "Optional(HK)" due to a prior error.