美文网首页
Swift - Range

Swift - Range

作者: ienos | 来源:发表于2021-12-19 18:13 被阅读0次

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")
}

相关文章

网友评论

      本文标题:Swift - Range

      本文链接:https://www.haomeiwen.com/subject/nlyofrtx.html