實例方法
relative(to:)
返回給定集合中此範圍表達式說明的索引範圍。
必需的。
聲明
func relative<C>(to collection: C) -> Range<Self.Bound> where C : Collection, Self.Bound == C.Index
返回值
適合切片 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 RangeExpression ~=(_:_:)用法及代碼示例
- Swift RangeReplaceableCollection insert(_:at:)用法及代碼示例
- Swift Range clamped(to:)用法及代碼示例
- Swift RangeReplaceableCollection filter(_:)用法及代碼示例
- Swift RangeReplaceableCollection removeFirst(_:)用法及代碼示例
- Swift RangeReplaceableCollection用法及代碼示例
- Swift RangeReplaceableCollection removeSubrange(_:)用法及代碼示例
- Swift RangeReplaceableCollection replaceSubrange(_:with:)用法及代碼示例
- Swift RangeReplaceableCollection removeFirst()用法及代碼示例
- Swift RangeReplaceableCollection remove(at:)用法及代碼示例
- Swift Range overlaps(_:)用法及代碼示例
- Swift RangeReplaceableCollection append(_:)用法及代碼示例
- Swift RangeReplaceableCollection +=(_:_:)用法及代碼示例
- Swift Range用法及代碼示例
- Swift Range endIndex用法及代碼示例
- Swift RangeReplaceableCollection removeAll(where:)用法及代碼示例
- Swift Range ~=(_:_:)用法及代碼示例
- Swift RangeReplaceableCollection +(_:_:)用法及代碼示例
- Swift Range isEmpty用法及代碼示例
- Swift RangeReplaceableCollection init(repeating:count:)用法及代碼示例
- Swift RangeReplaceableCollection insert(contentsOf:at:)用法及代碼示例
- Swift Range ==(_:_:)用法及代碼示例
- Swift Range index(_:offsetBy:)用法及代碼示例
- Swift RangeReplaceableCollection append(contentsOf:)用法及代碼示例
- Swift RandomNumberGenerator用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 RangeExpression relative(to:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。