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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
