Swift(beta 3)“NSDictionary?不符合协议'Equatable'" [英] Swift (beta 3) "NSDictionary? does not conform to protocol 'Equatable'"
问题描述
自从更新到最新的Xcode 6 DP3以来,我的Swift代码中出现了一些警告和错误。大多数已通过采用新更改的语法解决,但有一个错误似乎很奇怪。
I've had a fair few warnings and errors in my Swift code since updating to the latest Xcode 6 DP3. Most have been resolved by adopting the newly changed syntax however there is one error which seems strange.
以下代码给出错误输入'NSDictionary? '不符合协议'Equatable'
:
if (launchOptions != nil && launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] != nil) {
有没有人有解决方案?我可能在这里忽略了一些简单的东西..!
Does anyone have a solution? I'm probably overlooking something simple here..!
谢谢
推荐答案
Beta 3中存在回归导致可选< T>
无法与 nil
进行比较,如果 T
不是 Equatable
或可比较
。
There is a regression in Beta 3 causing that Optional<T>
cannot be compared with nil
if T
is not Equatable
or Comparable
.
这是由于删除了定义了相等运算符的 _Nil
类型而导致的错误。 nil
现在是一个文字。该问题已由Chris Lattner在 Apple Dev论坛上确认
It's a bug caused by the removal of the _Nil
type for which the equality operators were defined. nil
is now a literal. The bug has been confirmed by Chris Lattner on Apple Dev Forums
一些解决方法:
您仍然可以使用 .getLogicValue()
if launchOptions.getLogicValue() && ... {
或直接
if launchOptions && ... { //calls .getLogicValue()
或者您可以使用Javascript对象布尔 解决方案
or you can use the "Javascript object to boolean" solution
var bool = !!launchOptions
(第一个!
调用 getLogicValue
并否定,第二个!
再次否定)
(first !
calls the getLogicValue
and negates, the second !
negates again)
或者,您可以自己定义这些相等运算符,直到它们修复它:
or, you can define those equality operators by yourself until they fix it:
//this is just a handy struct that will accept a nil literal
struct FixNil : NilLiteralConvertible {
static func convertFromNilLiteral() -> FixNil {
return FixNil()
}
}
//define all equality combinations
func == <T>(lhs: Optional<T>, rhs: FixNil) -> Bool {
return !lhs.getLogicValue()
}
func != <T>(lhs: Optional<T>, rhs: FixNil) -> Bool {
return lhs.getLogicValue()
}
func == <T>(lhs: FixNil, rhs: Optional<T>) -> Bool {
return !rhs.getLogicValue()
}
func != <T>(lhs: FixNil, rhs: Optional<T>) -> Bool {
return rhs.getLogicValue()
}
示例:
class A {
}
var x: A? = nil
if x == nil {
println("It's nil!")
}
else {
println("It's not nil!")
}
但是,这种解决方法可能会导致其他微妙的问题(它可能同样有效)到Beta 2中的 _Nil
类型已被删除,因为它导致了问题......)。
However, this workaround might cause other subtle problems (it probably works similarily to the _Nil
type in Beta 2 which was removed because it was causing problems...).
这篇关于Swift(beta 3)“NSDictionary?不符合协议'Equatable'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!