Range 和 CloseRange
/// Range
let range = 0..<3
/// CloseRange
let closeRange = 0...3
判断一个值是否在范围内
以 Int 为例子
let intTarget: Int = 3
let intRange = 0...12
if intRange.contains(intTarget) {
print("Range contains \(intTarget)")
}
if intRange ~= intTarget {
print("Range contains \(intTarget)")
}
其中范围分为两种: Range 和 CloseRange,它们均需要实现 Comparable,Comparable 的协议如下
protocol Comparable: Equatable {
static func < (lhs: Self, rhs: Self) -> Bool
static func <= (lhs: Self, rhs: Self) -> Bool
static func >= (lhs: Self, rhs: Self) -> Bool
static func > (lhs: Self, rhs: Self) -> Bool
}
Comparable 继承 Equatable
protocol Equatable {
static func == (lhs: Self, rhs: Self) -> Bool
}
自定义 Range 实现
以 Person 为例子
struct Person {
var age: Int = 0
}
extension Person: Comparable {
static func < (lhs: Person, rhs: Person) -> Bool {
return lhs.age < rhs.age
}
}
extension Person: Equatable {
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.age == rhs.age
}
}
/// 猜测底层已经实现了 Comparable 的部分协议
/*
extension Comparable {
// 小于等于
static func <= (lhs: Self, rhs: Self) -> Bool {
return lhs < rhs && lhs == rhs
}
// 大于等于
static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
// 大于
static func > (lhs: Self, rhs: Self) -> Bool {
return !(lhs <= rhs)
}
}
*/
这样也就可以实现对 Range 的判断
let jerry = Person.init(age: 12)
let tommy = Person.init(age: 23)
let personRange = jerry...tommy
let gary = Person.init(age: 20)
if personRange.contains(gary) {
print("gary contain in jerry...tommy")
}
网友评论