How do I implement Swift#39;s Comparable protocol?(如何实现 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 协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何实现 Swift 的 Comparable 协议?


基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01