I got error when I convert my codes from Xcode7.2 to Xcode7.3

85 Views Asked by At

The error message says that Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'? I replaced String to NSArray but it didn't work. Does anyone know how to fix this?

returnFirebaseUrl(self.myRootRef).queryLimitedToLast(1000).observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) in

            self.showProgressHUD()

            // 3 codes below are the reason why I got error for.
            let text = snapshot.value["text"] as? String
            let sender = snapshot.value["from"] as? String
            let name = snapshot.value["name"] as? String


            var isOutGoing:Bool

            if sender == GetUserId(){
                isOutGoing = true
            }else{
                isOutGoing = false
            }

            let mediaItem = self.createPhotoItem(Const.S3_URL + text!, isOutgoing: isOutGoing)

            var message:JSQMessage
            if text!.hasSuffix(".jpg"){
                message = JSQMessage(senderId: sender, displayName: name, media: mediaItem)

            }else{
                message = JSQMessage(senderId: sender, displayName: name, text: text)
            }
            self.messages?.append(message)
2

There are 2 best solutions below

2
On

Looks like you also need to unwrap snapshot.value.

Something like thism probably:

guard let value = snapshot.value, 
    text = value["text"] as? String,
    sender = value["from"] as? String,
    name = value["name"] as? String else {
        fatalError("Oops, one of the values was nil")
}

// here you can use unwrapped text, sender and name
2
On

You need to unwrap snapshot.value in order to be able to use it as a Dictionary. As a guide is not safe to 'force unwrap' using '!' as it might lead to crashes.

What you could try is something like the following:

    if let valueDictionary = snapshot.value as? Dictionary<String, AnyObject> {
       let text = snapshot.value["text"] as? String //this will still be optional and might need to carefully unwrap
       etc etc
    }