Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

ios - Swift (beta 3) "NSDictionary? does not conform to protocol 'Equatable'"

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.

The following code gives the error Type 'NSDictionary?' does not conform to protocol 'Equatable':

if (launchOptions != nil && launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] != nil) {

Does anyone have a solution? I'm probably overlooking something simple here..!

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a regression in Beta 3 causing that Optional<T> cannot be compared with nil if T is not Equatable or Comparable.

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

Some workarounds:

You can still use .getLogicValue()

if launchOptions.getLogicValue() && ... {

or directly

if launchOptions && ... { //calls .getLogicValue()

or you can use the "Javascript object to boolean" solution

var bool = !!launchOptions

(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()
}

Example:

class A {
}

var x: A? = nil

if x == nil {
    println("It's nil!")
}
else {
    println("It's not 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...).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...