ArraySlice
Array
、 ContiguousArray
或 ArraySlice
實例的切片。聲明
@frozen struct ArraySlice<Element>
概述
ArraySlice
類型使您可以快速高效地對較大數組的各個部分執行操作。 ArraySlice
實例不是將切片的元素複製到新存儲,而是將視圖呈現到更大數組的存儲上。而且因為 ArraySlice
提供與 Array
相同的接口,您通常可以在切片上執行與原始數組相同的操作。
有關使用數組的更多信息,請參閱 Array
和 ContiguousArray
,其中 ArraySlice
共享大多數屬性和方法。
切片是數組的視圖
例如,假設您有一個數組,其中包含一個會話期間每個類的缺勤次數。
let absences = [0, 2, 0, 4, 0, 3, 1, 0]
您想將會話前半部分的缺勤情況與後半部分的缺勤情況進行比較。為此,首先創建 absences
數組的兩個切片。
let midpoint = absences.count / 2
let firstHalf = absences[..<midpoint]
let secondHalf = absences[midpoint...]
firstHalf
和 secondHalf
切片都不會分配自己的任何新存儲。相反,每個都在absences
數組的存儲上呈現一個視圖。
您可以在切片上調用您可能在 absences
數組上調用過的任何方法。要了解哪一半缺勤較多,請使用reduce(_:_:)
方法計算每個總和。
let firstHalfSum = firstHalf.reduce(0, +)
let secondHalfSum = secondHalf.reduce(0, +)
if firstHalfSum > secondHalfSum {
print("More absences in the first half.")
} else {
print("More absences in the second half.")
}
// Prints "More absences in the first half."
切片維持指數
與 Array
和 ContiguousArray
不同,ArraySlice
實例的起始索引並不總是零。切片為相同元素維護較大數組的相同索引,因此切片的起始索引取決於它的創建方式,讓您可以對完整數組或切片執行基於索引的操作。
在集合及其子序列之間共享索引是 Swift 集合算法設計的重要部分。假設您的任務是查找會話中前兩天缺勤的情況。要查找相關兩天的指數,請執行以下步驟:
-
調用
firstIndex(where:)
以查找absences
數組中大於零的第一個元素的索引。 -
在步驟 1 中找到的索引之後開始創建
absences
數組的切片。 -
再次調用
firstIndex(where:)
,這次是在步驟 2 中創建的切片上。在某些語言中,您可能會將起始索引傳遞給indexOf
方法以查找第二天,而在 Swift 中,您對切片的切片執行相同的操作原始數組。 -
使用在原始
absences
數組上的步驟 1 和 3 中找到的索引打印結果。
以下是這些步驟的實現:
if let i = absences.firstIndex(where: { $0 > 0 }) { // 1
let absencesAfterFirst = absences[(i + 1)...] // 2
if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3
print("The first day with absences had \(absences[i]).") // 4
print("The second day with absences had \(absences[j]).")
}
}
// Prints "The first day with absences had 2."
// Prints "The second day with absences had 4."
特別要注意 j
是缺勤的第二天的索引,它是在原始數組的切片中找到的,然後用於訪問原始 absences
數組本身中的值。
可用版本
相關用法
- Swift ArraySlice starts(with:)用法及代碼示例
- Swift ArraySlice reduce(_:_:)用法及代碼示例
- Swift ArraySlice prefix(through:)用法及代碼示例
- Swift ArraySlice prefix(upTo:)用法及代碼示例
- Swift ArraySlice randomElement()用法及代碼示例
- Swift ArraySlice map(_:)用法及代碼示例
- Swift ArraySlice reversed()用法及代碼示例
- Swift ArraySlice append(contentsOf:)用法及代碼示例
- Swift ArraySlice removeSubrange(_:)用法及代碼示例
- Swift ArraySlice shuffled()用法及代碼示例
- Swift ArraySlice suffix(from:)用法及代碼示例
- Swift ArraySlice lastIndex(of:)用法及代碼示例
- Swift ArraySlice prefix(_:)用法及代碼示例
- Swift ArraySlice joined()用法及代碼示例
- Swift ArraySlice insert(contentsOf:at:)用法及代碼示例
- Swift ArraySlice sorted(by:)用法及代碼示例
- Swift ArraySlice init(arrayLiteral:)用法及代碼示例
- Swift ArraySlice reserveCapacity(_:)用法及代碼示例
- Swift ArraySlice isEmpty用法及代碼示例
- Swift ArraySlice enumerated()用法及代碼示例
- Swift ArraySlice firstIndex(of:)用法及代碼示例
- Swift ArraySlice removeAll(where:)用法及代碼示例
- Swift ArraySlice forEach(_:)用法及代碼示例
- Swift ArraySlice +(_:_:)用法及代碼示例
- Swift ArraySlice index(_:offsetBy:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ArraySlice。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。