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

℡╲_俬逩灬. 提交于 2019-12-01 20:47:40

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 {...}

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.

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