如何实现 Swift 的 Comparable 协议?

How do I implement Swift#39;s Comparable protocol?(如何实现 Swift 的 Comparable 协议?)
本文介绍了如何实现 Swift 的 Comparable 协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中使用 Comparable 协议?在声明中它说我必须实现三个操作 <、<= 和 >=.我把所有这些都放在课堂上,但它不起作用.我还需要拥有这三个吗?因为应该可以从一个推导出所有这些.

How do I use the Comparable protocol in Swift? In the declaration it says I'd have to implement the three operations <, <= and >=. I put all those in the class but it doesn't work. Also do I need to have all three of them? Because it should be possible to deduce all of them from a single one.

推荐答案

Comparable 协议扩展了 Equatable 协议 -> 实现它们两个

The Comparable protocol extends the Equatable protocol -> implement both of them

在 Apple's Reference 中是来自 Apple (在 Comparable 协议参考中)你可以看到你应该怎么做:不要把操作实现放在类中,而是放在外部/全局范围内.此外,您只需实现 Comparable 协议中的 < 运算符和 Equatable 协议中的 == 运算符.

In Apple's Reference is an example from Apple (within the Comparable protocol reference) you can see how you should do it: Don't put the operation implementations within the class, but rather on the outside/global scope. Also you only have to implement the < operator from Comparable protocol and == from Equatable protocol.

正确示例:

class Person : Comparable {
    let name : String

    init(name : String) {
        self.name = name
    }
}

func < (lhs: Person, rhs: Person) -> Bool {
    return lhs.name < rhs.name
}

func == (lhs: Person, rhs: Person) -> Bool {
    return lhs.name == rhs.name
}

let paul = Person(name: "Paul")
let otherPaul = Person(name: "Paul")
let ben = Person(name: "Ben")

paul > otherPaul  // false
paul <= ben       // false
paul == otherPaul // true

这篇关于如何实现 Swift 的 Comparable 协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)