Swift 2.2 breaks optionals/unwrapping optionals

若如初见. 提交于 2019-12-13 13:32:12

问题


Swift 2.2 has broken almost all my code. Even this simple string assigning to label doesn't work anymore:

cell.categoryName.text = peopleArray![indexPath.row]["Name"] as? String

The error says "Downcast from 'String?!' to 'String' only unwraps optionals, did you mean to use '!!'?"

What changes do I have to do now.

EDIT:

More Problems:

if (dict["data"]!["DataDetails"] as! NSArray).count == 0 {
}

Due to this I am getting a segmentation fault and the error shows this: warning: cast from 'String?!' to unrelated type 'NSArray' always fails

UPDATE:

I was using NSDictionaries, NSArrays in my classes that seems to cause the problem. Changing all the literals from Obj-C to swift made the code work properly. So, I will also recommend other developers to prefer swift literals.


回答1:


it seems there are some slight differences when using the swift types and the objective-c NS... types

eg

let dic:NSDictionary? = ["a":"a"]

let str:NSString? = dic!["a"] as? NSString

let dic2:Dictionary? = ["b":"b"]

let str2:String? = dic2!["b"] //dont need to do any casting, already optional

print(str)
print(str2)

prints

Optional(a)
Optional("b")

so depending on how your array / dictionary is defined, you might need different casting/unwrapping



来源:https://stackoverflow.com/questions/36171958/swift-2-2-breaks-optionals-unwrapping-optionals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!