實例方法
relative(to:)
返回給定集合中此範圍表達式說明的索引範圍。
聲明
func relative<C>(to collection: C) -> Range<Bound> where Bound == C.Index, C : Collection
當
Bound
符合 Comparable
時可用。返回值
適合切片 collection
的範圍。返回的範圍是 not
保證在 collection
的範圍內。調用者應該對返回值應用相同的先決條件,就像他們對用戶直接提供的範圍一樣。
參數
collection
評估與此範圍表達式相關的集合。
詳述
您可以使用relative(to:)
方法將可能缺少一個或兩個端點的範圍表達式轉換為兩側有界的具體範圍。下麵的示例使用此方法將不超過 4
的部分範圍轉換為半開範圍,使用數組實例添加範圍的下限。
let numbers = [10, 20, 30, 40, 50, 60, 70]
let upToFour = ..<4
let r1 = upToFour.relative(to: numbers)
// r1 == 0..<4
r1
範圍的下端以 0
為界,因為這是 numbers
數組的起始索引。當傳遞給 relative(to:)
的集合以不同的索引開始時,該索引將用作下限。下一個示例從索引 2
開始創建一個 numbers
切片,然後使用帶有 relative(to:)
的切片將 upToFour
轉換為具體範圍。
let numbersSuffix = numbers[2...]
// numbersSuffix == [30, 40, 50, 60, 70]
let r2 = upToFour.relative(to: numbersSuffix)
// r2 == 2..<4
僅當您需要它產生的具體範圍時才使用此方法。要使用範圍表達式訪問集合的切片,請使用集合的通用下標,該下標使用範圍表達式作為其參數。
let numbersPrefix = numbers[upToFour]
// numbersPrefix == [10, 20, 30, 40]
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift ClosedRange index(_:offsetBy:)用法及代碼示例
- Swift ClosedRange ~=(_:_:)用法及代碼示例
- Swift ClosedRange clamped(to:)用法及代碼示例
- Swift ClosedRange subscript(_:)用法及代碼示例
- Swift ClosedRange ==(_:_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:)用法及代碼示例
- Swift ClosedRange.Index ..<(_:_:)用法及代碼示例
- Swift ClosedRange用法及代碼示例
- Swift ClosedRange.Index ...(_:_:)用法及代碼示例
- Swift ClosedRange.Index ...(_:)用法及代碼示例
- Swift CollectionDifference firstIndex(of:)用法及代碼示例
- Swift Collection prefix(upTo:)用法及代碼示例
- Swift ContiguousArray forEach(_:)用法及代碼示例
- Swift CollectionOfOne contains(_:)用法及代碼示例
- Swift Collection first用法及代碼示例
- Swift Character lowercased()用法及代碼示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代碼示例
- Swift CollectionOfOne compactMap(_:)用法及代碼示例
- Swift CollectionDifference contains(where:)用法及代碼示例
- Swift CollectionOfOne last(where:)用法及代碼示例
- Swift Collection dropLast(_:)用法及代碼示例
- Swift ContiguousArray reserveCapacity(_:)用法及代碼示例
- Swift Comparable ...(_:)用法及代碼示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代碼示例
- Swift ContiguousArray elementsEqual(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ClosedRange relative(to:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。