当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift LazyPrefixWhileSequence prefix(through:)用法及代码示例


实例方法

prefix(through:)

返回从集合开始到指定位置的子序列。

声明

func prefix(through position: Self.Index) -> Self.SubSequence

返回值

直到并包括给定位置的子序列。

参数

position

要包含在结果子序列中的最后一个元素的索引。 position 必须是不等于 endIndex 属性的集合的有效索引。

详述

生成的子序列includes 元素在through 参数指定的位置。以下示例在整数数组中搜索数字 40 的索引,然后打印该数组的前缀,直至并包括该索引:


let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

使用prefix(through:) 方法相当于使用部分封闭范围作为集合的下标。下标符号优于 prefix(through:)


if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 LazyPrefixWhileSequence prefix(through:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。