本文主要讲解 Range 家族类的一些实现细节和 Swift 中面向协议编程的一些具体表现。为了方便起见,不管是 class 或者 struct 都统称为『类』。git
在 Swift 4.0 以前 Range 家族一共有 4 种类型:github
let rang: Range = 0.0..<1.0 // 半开区间 let closedRange: ClosedRange = 0.0...1.0 // 闭区间 let countableRange: CountableRange = 0..<1 // Countable 半开区间 let countableClosedRange: CountableClosedRange = 0...1 // Countable 闭区间
以后 Swift 4.0 上新增了 4 种类型:编程
let partialRangeThrough: PartialRangeThrough = ...1.0 // 单侧区间 let partialRangeFrom: PartialRangeFrom = 0.0... // 单侧区间 let partialRangeUpTo: PartialRangeUpTo = ..<1.0 // 单侧区间 let countablePartialRangeFrom: CountablePartialRangeFrom = 1... // Countable 单侧区间
但到了 Swift 4.2 又只剩下 5 种类型,分别是:Range
、ClosedRange
、PartialRangeThrough
、PartialRangeFrom
、PartialRangeUpTo
,全部的 Countable 类型都是对应的 typealias
。swift
public typealias CountableRange<Bound> = Range<Bound> public typealias CountableClosedRange<Bound> = ClosedRange<Bound> public typealias CountablePartialRangeFrom<Bound> = PartialRangeFrom<Bound>
Range 的全部类型都是一个拥有 Bound 泛型的 struct,而且这个 Bound 必须继承 Comparable 协议。app
public struct Range<Bound> where Bound : Comparable public struct ClosedRange<Bound> where Bound : Comparable public struct PartialRangeThrough<Bound> where Bound : Comparable public struct PartialRangeFrom<Bound> where Bound : Comparable public struct PartialRangeUpTo<Bound> where Bound : Comparable
在 swift 标准库中绝大多数基础类型都实现了此协议,因此包括 String
、Date
和 IndexPath
等。ide
let stringRange = "a"..<"z" let dateRange = Date()...Date() let indexRange = IndexPath(item: 0, section: 0)...IndexPath(row: 1, section: 0)
当须要用一个自定义的类建立 Range 也只是须要继承 Comparable 协议,并实现相应方法便可,例如idea
struct Foo: Comparable { var value: Int static func < (lhs: Foo, rhs: Foo) -> Bool { return lhs.value < rhs.value } init(_ v: Int) { value = v } } let range = Foo(1)...Foo(20) foo.contains(Foo(2)) // true
并且 contains(:)
也被自动的实现了,这其实归功于 RangeExpression 协议:spa
public func contains(_ element: Self.Bound) -> Bool
究其缘由是每一个 Range 类型都有一个 extension:当泛型 Bound 遵照 Comparable 时扩展相应的类以现实 RangeExpression 协议。code
extension Range : RangeExpression where Bound : Comparable
extension ClosedRange : RangeExpression where Bound : Comparable
extension PartialRangeThrough : RangeExpression where Bound : Comparable
extension PartialRangeFrom : RangeExpression where Bound : Comparable
extension PartialRangeUpTo : RangeExpression where Bound : Comparable
试想一下若是用面向对象的语言通常是如何实现 contains(:)
方法的?orm
前面讲到在 Swift 4.2 上全部的 Countable 类型都是 typealias,是否具备 Countable 能力被抽象到泛型 Bound 上,以 ClosedRange 为例
extension ClosedRange : Sequence where Bound : Strideable, Bound.Stride : SignedInteger { /// A type representing the sequence's elements. public typealias Element = Bound /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator<ClosedRange<Bound>> }
能够看到为了继承 Sequence 协议,泛型 Bound 须要先继承 Strideable
,Strideable
协议定义以下:
public protocol Strideable : Comparable { /// A type that represents the distance between two values. associatedtype Stride : Comparable, SignedNumeric public func distance(to other: Self) -> Self.Stride public func advanced(by n: Self.Stride) -> Self }
它有一个绑定类型 Stride 和两个须要实现的方法,那么Bound.Stride : SignedInteger
表示的就是Strideable
的绑定类型 Stride
须要继承 SignedInteger
。
总结下来 swift 经过泛型约束、协议绑定类型约束再结合 extension 能力,把 Countable 能力被抽象到泛型 Bound 上,最终由泛型 Bound 来决定 Range 是否具备 Sequence 能力。
或许你只知道经过 Int 建立的 Range,它就是一个CountableRange
,然而为何是?首先 Int 继承于 FixedWidthInteger
, SignedInteger
public struct Int : FixedWidthInteger, SignedInteger
SignedInteger 又继承于 BinaryInteger
, SignedNumeric
public protocol SignedInteger : BinaryInteger, SignedNumeric { }
BinaryInteger 在必定条件下又继承于 Strideable
public protocol BinaryInteger : CustomStringConvertible, Hashable, Numeric, Strideable where Self.Magnitude : BinaryInteger, Self.Magnitude == Self.Magnitude.Magnitude
继续查看BinaryInteger
对 Strideable
实现:
extension BinaryInteger { public func distance(to other: Self) -> Int public func advanced(by n: Int) -> Self }
会发现 Stride 类型就是 Int, 而 Int 自己就是继承于 SignedInteger
,这样子就符合前面提到的 Bound.Stride : SignedInteger
条件。最后别忘了另一个限定条件
where Self.Magnitude : BinaryInteger, Self.Magnitude == Self.Magnitude.Magnitude
Magnitude 是 Numeric
协议的绑定类型,Numeric
定义以下:
public protocol Numeric : Equatable, ExpressibleByIntegerLiteral { associatedtype Magnitude : Comparable, Numeric public var magnitude: Self.Magnitude { get } }
但未发现 BinaryInteger
有任何的 extension 给定 Magnitude 的类型。这只能说明 Magnitude 会在具体的类上被指定,回到 Int 上果真找到 Magnitude
。
public struct Int : FixedWidthInteger, SignedInteger { public typealias Magnitude = UInt }
继续查看 UInt
public struct UInt : FixedWidthInteger, UnsignedInteger { public typealias Magnitude = UInt }
UnsignedInteger
又继承于 BinaryInteger
public protocol UnsignedInteger : BinaryInteger { }
因此Self.Magnitude : BinaryInteger, Self.Magnitude == Self.Magnitude.Magnitude
就至关于 Int.UInt : BinaryInteger, Int.UInt == Int.UInt.UInt
。至此 Int 类型知足了一切条件,事实上不只是 Int 整个 Int 家族和 UInt 家族类型都是符合这些条件,下面是关于Int
和 UInt
粗略协议继承关系。
+---------------+ | Comparable | +-------+-------+ ^ | +-------------+ +-----+-------+ +------>+ Numeric | | Strideable | | +------------++ +-----+-------+ | ^ ^ | | | +-------+-------+ +---+----------+----+ | SignedNumeric | | BinaryInteger | +------+--------+ +---+-----+-----+---+ ^ +-----------^ ^ ^----------+ | | | | +------+---------++ +-----------+--------+ +----+-------------+ | SignedInteger | | FixedWidthInteger | | UnsignedInteger | +---------------+-+ +-+----------------+-+ +--+---------------+ ^ ^ ^ ^ | | | | | | | | ++--------+-+ ++-------+--+ |Int family | |UInt family| +-----------+ +-----------+
struct Foo { var value: Int init(_ v: Int) { value = v } } extension Foo: Strideable { func distance(to other: Foo) -> Int { return other.value - self.value } func advanced(by n: Int) -> Foo { var result = self result.value += n return result } }
Foo 继承 Strideable 的同时其绑定也被指定为 Int,这样子就能够建立自定义类型的 Range 了,而且继承于 Sequence 。
let fooRange = Foo(1)...Foo(20) fooRange.contains(Foo(2)) Array((Foo(1)..<Foo(20))) for item in fooRange { print(item) }
Swift 做为一门面向协议编程的语言,在 Range 的实现上可见一斑,随着 SE-0142、SE-0143提案分别在 Swift 4.0 和 Swift 4.2 中被加入以后更是增强了在这方面的能力。