先附上代码:
//自定义结构体类型,进行大小比较
struct Games {
var winCount: Int
var loseCount: Int
}
let g1 = Games(winCount: 2, loseCount: 2)
let g2 = Games(winCount: 3, loseCount: 1)
extension Games: Comparable {} //此协议的实现方法写在外面
//协议方法实现的逻辑由编程者自己定义,要符合常规的逻辑
//<是方法名
func <(b1: Games, b2: Games) -> Bool {
let gScore1 = b1.winCount - b1.loseCount
let gScore2 = b2.winCount - b2.loseCount
return gScore1 < gScore2
}
g1 < g2
跳转过去得到系统标准库中Comparable
的协议如下:
public protocol Comparable : Equatable {
/// A [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order)
/// over instances of `Self`.
@warn_unused_result
public func <(lhs: Self, rhs: Self) -> Bool
@warn_unused_result
public func <=(lhs: Self, rhs: Self) -> Bool
@warn_unused_result
public func >=(lhs: Self, rhs: Self) -> Bool
@warn_unused_result
public func >(lhs: Self, rhs: Self) -> Bool
}
问题是:
1.swift中协议里面声明的方法不是都需要实现的吗,这里为什么不需要?
2.Comparable
协议的方法为什么是在{ }外实现的?
To summarize:
1. Comparison of instances: Determine whether the values of two instances are the same
Equatable
Equatable protocol: The == method must be implemented, and the corresponding == method is selected based on comparing the data types of both parties.
2. Compare the sizes of two instances
Comparable
Comparable protocol: Inherited from Equatable, it must implement the == method in Equatable, and it must also implement the < method.
3. Why does the standard library protocol not use the keyword @objc optional in the protocol to indicate that other methods are optional, and there is no need to implement them after signing the protocol?
//Comparable protocol in the library.
Havthgem’s answer: The Swift static library has a default implementation for the remaining comparison calculations, based on your custom == and <
The above are comments from the Comparable protocol. If you still don’t understand, just reply.