Swift可选项-从'x'到'x'的条件强制转换警告始终会成功 [英] Swift optionals - warning on conditional cast from 'x' to 'x' always succeeds
问题描述
我想知道是否有一种方法可以关闭/避免键值为已知值的if let...NSUserDefaults
结构上的xcode中的黄色"警告.
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.
例如:
if let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey") as? Int {...}
由于if let
,我必须使用as?
.但是,由于我使用的是已知的值类型(在这种情况下为整数),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?
推荐答案
我的建议是解决该问题,而不是静默警告. :)
My suggestion would be to address the issue instead of silencing the warnings. :)
NSUserDefaults.standardUserDefaults().integerForKey("myKey")
不返回Optional,并且类型是已知的,因此您既不需要使用if let
进行可选绑定,也不需要使用as?
进行类型转换.
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?
.
就这样:
let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey")
就足够了,因为如果.integerForKey
无法获得实际值,它只会返回0
.
will suffice, since .integerForKey
just returns 0
if it can't get the actual value.
如果您不喜欢这种获取默认值的行为(我不喜欢),请不要使用.integerForKey
并将objectForKey
与可选绑定一起使用,并键入强制类型转换.就像您之前所做的一样,但是用.objectForKey
替换了.integerForKey
.这样,如果键的值不可访问,而不是默认值,您将得到实际的nil.
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 {...}
这篇关于Swift可选项-从'x'到'x'的条件强制转换警告始终会成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!