为什么快速编译器在具有/不具有Equatable协议的情况下与相等运算符的行为不同 [英] why swift compiler behaves differently with equality operator with/without Equatable protocol

查看:70
本文介绍了为什么快速编译器在具有/不具有Equatable协议的情况下与相等运算符的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 4.0的Playground中,我有一个非常简单的类,它覆盖了==运算符.

I have a very simple class in a Playground in Swift 4.0 that overrides the == operator.

我不明白为什么当类继承/不继承 Equatable 协议时,Swift编译器的行为不一样.

I'm not understanding why the Swift complier doesn't behave the same when the class inherits/doesn't inherit Equatable protocol.

继承Equatable协议时,请参见类

Here the class when inheriting Equatable protocol

class Test: Equatable  {
    var value = 0

    init(_ initialValue:Int) {
        value = initialValue
    }

    static func == (lhs:Test, rhs:Test) -> Bool {
        return lhs.value == rhs.value ? true : false
    }
}

let test1 = Test(0)
var test4:Test? = nil

if test1 == test4 {
    print("test1 and test4 are equals")
} else {
    print("test1 not equals to test4")
}

执行此代码时,显示"test1不等于test4".这是预期的行为.

When this code executes it displays "test1 not equals to test4". It's the expected behavior.

接下来,当我从类中删除"Equatable"协议

Next, when I just remove the "Equatable" protocol from the class

class Test  {
    var value = 0

    init(_ initialValue:Int) {
        value = initialValue
    }

    static func == (lhs:Test, rhs:Test) -> Bool {
        return lhs.value == rhs.value ? true : false
    }
}

let test1 = Test(0)
let test3 = Test(0)

var test4:Test? = nil


if test1 == test4 {
    print("test1 and test4 are equals")
} else {
    print("test1 not equals to test4")
}

我在行上遇到编译错误

if test1 == test4 {

并显示以下消息:可选类型'Test?'的值尚未解包;您是要使用!"还是?"?

为什么有/没有Equatable的行为有所不同?

Why the behavior is different with/without Equatable?

实际上,当我从Equatable继承该类时,我也期望出现相同的编译错误,因为我将非可选与可选进行了比较.

In fact, I was also expecting the same compilation error when the class inherits from Equatable because I compare a non-optional with an optional.

当类继承Equatable时将非可选与可选进行比较是否安全?

Is it safe to compare a non-optional with an optional when a class inherits Equatable ?

推荐答案

有一个 运算符

public func ==<T>(lhs: T?, rhs: T?) -> Bool where T : Equatable

允许比较两个可选值(如果基础 类型是Equatable.在您的第一种情况下会调用该运算符

which allows to compare two optional values if the underlying type is Equatable. That operator is called in your first case

let test1 = Test(0)
var test4:Test? = nil

if test1 == test4 { ... }

(并且左操作数会自动包装为可选值.)

(and the left operand is automatically wrapped into an optional.)

如果Test不符合Equatable,则该运算符会 不匹配,因此没有==运算符取两个Test? 操作数.因此,编译器错误.

If Test does not conform to Equatable then that operator does not match, so that there is no == operator taking two Test? operands. Therefore the compiler error.

这篇关于为什么快速编译器在具有/不具有Equatable协议的情况下与相等运算符的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆