用法一
replaceSubrange(_:with:)
声明
mutating func replaceSubrange<C, R>(
_ subrange: R,
with newElements: C
) where C : Collection, R : RangeExpression, Self.Element == C.Element, Self.Index == R.Bound
参数
subrange
要替换的集合的子范围。范围的边界必须是集合的有效索引。
newElements
要添加到集合中的新元素。
详述
此方法具有从集合中删除指定范围的元素并在同一位置插入新元素的效果。新元素的数量不必与要移除的元素的数量相匹配。
在此示例中,整数数组中间的三个元素被 Repeated<Int>
实例的五个元素替换。
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print(nums)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
如果您将零长度范围作为 subrange
参数传递,此方法会在 subrange.startIndex
处插入 newElements
的元素。最好调用 insert(contentsOf:at:)
方法。
同样,如果您将零长度集合作为newElements
参数传递,则此方法将删除给定子范围中的元素而不进行替换。最好调用removeSubrange(_:)
方法。
调用此方法可能会使用于此集合的任何现有索引无效。
可用版本
用法二
replaceSubrange(_:with:)
声明
mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newElements: C
) where Element == C.Element, C : Collection
参数
subrange
要替换的数组的子范围。子范围的开始和结束必须是数组的有效索引。
newElements
要添加到数组的新元素。
详述
此方法具有从数组中删除指定范围的元素并将新元素插入相同位置的效果。新元素的数量不必与要移除的元素的数量相匹配。
在此示例中,整数数组中间的三个元素被 Repeated<Int>
实例的五个元素替换。
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print(nums)
// Prints "[10, 1, 1, 1, 1, 1, 50]"
如果您将零长度范围作为 subrange
参数传递,此方法会在 subrange.startIndex
处插入 newElements
的元素。最好调用 insert(contentsOf:at:)
方法。
同样,如果您将零长度集合作为newElements
参数传递,则此方法将删除给定子范围中的元素而不进行替换。最好调用removeSubrange(_:)
方法。
可用版本
相关用法
- Swift ArraySlice reduce(_:_:)用法及代码示例
- Swift ArraySlice reversed()用法及代码示例
- Swift ArraySlice removeSubrange(_:)用法及代码示例
- Swift ArraySlice reserveCapacity(_:)用法及代码示例
- Swift ArraySlice removeAll(where:)用法及代码示例
- Swift ArraySlice remove(at:)用法及代码示例
- Swift ArraySlice reverse()用法及代码示例
- Swift ArraySlice removeFirst()用法及代码示例
- Swift ArraySlice reduce(into:_:)用法及代码示例
- Swift ArraySlice removeFirst(_:)用法及代码示例
- Swift ArraySlice randomElement()用法及代码示例
- Swift ArraySlice randomElement(using:)用法及代码示例
- Swift ArraySlice starts(with:)用法及代码示例
- Swift ArraySlice prefix(through:)用法及代码示例
- Swift ArraySlice prefix(upTo:)用法及代码示例
- Swift ArraySlice map(_:)用法及代码示例
- Swift ArraySlice append(contentsOf:)用法及代码示例
- 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:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 ArraySlice replaceSubrange(_:with:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。