Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift compilation error: Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'?

After upgrading to cocoapods 1.0, I get this compilation error for these lines of code:

var strName = String()
var strEmail = String()
var strFacebookID = String()
var strPassword = String()
var objHelper = Helper()

....

let strFirstName = result["first_name"] as! String
let strLastName = result["last_name"] as! String
self.strName = strFirstName + "_" + strLastName
self.strEmail = result["email"] as! String
self.strFacebookID = result["id"] as! String

Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'?

Here is a screenshot of the error in detail: https://i.sstatic.net/Z5Ssz.jpg

UPDATE: more code here: https://gist.github.com/anonymous/9c91c2eb1ccf269e78a118970468d1e8

like image 985
Axil Avatar asked Nov 23 '25 11:11

Axil


2 Answers

The error message says that result itself is an optional so you have to unwrap both result and the value respectively.

let strFirstName = result!["first_name"] as! String

or better using optional binding for more safety and less type casting

if let userData = result as? [String:String] {
   let strFirstName = userData["first_name"]!
   let strLastName = userData["last_name"]!
}
like image 189
vadian Avatar answered Nov 28 '25 16:11

vadian


result["key"] itself returns an optional, because there is a possibility that the key doesn't exist in the dictionary.

You'd need to first unwrap that optional, and then cast the returned value to a String. Try this:

let strFirstName = result["first_name"]! as! String

This is kind of a code smell, it's a lot of casting. Perhaps that dictionary should be of type [String : String] rather than what it is now.

like image 43
Alexander Avatar answered Nov 28 '25 16:11

Alexander