Swift optionals - warning on conditional cast from

2019-02-25 15:36发布

问题:

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.