Kenny L Kenny L - 7 months ago 13
Swift Question

Keep showing error on Swift 2.2, but can build successfully

After I upgraded to Xcode 7.3, Swift 2.2.

In the code,

func handleInfo(info: [NSObject: AnyObject]) {
let aps = info["aps"]
if let message = aps!["alert"] as? String {
.....
}
}


it will keep showing error for this line:

if let message = aps!["alert"] as? String


(Downcast from 'String?!' to 'Sting' only unwraps optionals; did you meant to use '!!'?)

But if I build and run, it will run successfully without any issue.
However, it pretty annoying that it keep showing up when I coding.

Anyway to fix that?

Answer

I finally figure out how to get rid of those errors. In Swift 2.2, it applies more strict rule for the data type.

So if there's a value of key in Dictionary is also a Dictionary, we will need to specify the data type of it.

So originally, we have the code:

func handleInfo(info: [NSObject: AnyObject]) {  
    let aps = info["aps"]  
    if let message = aps!["alert"] as? String {  
        ..... 
    }
}  

Now in Swift 2.2 it will be:

func handleInfo(info: [NSObject: AnyObject]) {  
    let aps = info["aps"] as! [String: AnyObject]
    if let message = aps!["alert"] as? String {  
        ..... 
    }
} 

Then errors showing in lines will be gone.