Swift optionals - warning on conditional cast from 'x' to 'x' always succeeds

回眸只為那壹抹淺笑 提交于 2019-12-20 02:45:19

问题


I was wondering if there is a way to turn off/avoid 'yellow' warnings in xcode on if let...NSUserDefaults constructs where the key is of a known value.

For example:

if let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey") as? Int {...}

Because of the if let I have to use as?. However, as I am using a known value type (in this case integer) the as? Int is effectively redundant - which is why I am getting the 'yellow warning'.

Thoughts? Is there a better way to code these types of constructs?


回答1:


My suggestion would be to address the issue instead of silencing the warnings. :)

NSUserDefaults.standardUserDefaults().integerForKey("myKey") does not return an Optional, and the type is known, so you don't need neither optional binding with if let nor type casting with as?.

Just this:

let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey")

will suffice, since .integerForKey just returns 0 if it can't get the actual value.

If you don't like this behavior of getting a default value (I don't), then don't use .integerForKey and use objectForKey with optional binding and type casting instead. Like you were doing first but with .objectForKey replacing .integerForKey. That way you'll get an actual nil if the value for the key is unreachable, not a default value.

if let x = NSUserDefaults.standardUserDefaults(). objectForKey("myKey") as? Int {...}



回答2:


First of all check always the signature:
-click on the symbol integerForKey: or look at Quick Help.

You will see:

func integerForKey(_ defaultName: String) -> Int

It reveals the return value is a non optional.

Non optionals can retrieved directly as described in Eric's answer without any type casting, optional binding causes an error.

That's one of the essential semantics in Swift.



来源:https://stackoverflow.com/questions/34354048/swift-optionals-warning-on-conditional-cast-from-x-to-x-always-succeeds

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