用法一
replaceSubrange(_:with:)
必需的。提供默認實現。
聲明
mutating func replaceSubrange<C>(
_ subrange: Range<Self.Index>,
with newElements: C
) where C : Collection, Self.Element == C.Element
參數
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, 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(_:)
方法。
調用此方法可能會使用於此集合的任何現有索引無效。
可用版本
相關用法
- Swift RangeReplaceableCollection removeFirst(_:)用法及代碼示例
- Swift RangeReplaceableCollection removeSubrange(_:)用法及代碼示例
- Swift RangeReplaceableCollection removeFirst()用法及代碼示例
- Swift RangeReplaceableCollection remove(at:)用法及代碼示例
- Swift RangeReplaceableCollection removeAll(where:)用法及代碼示例
- Swift RangeReplaceableCollection insert(_:at:)用法及代碼示例
- Swift RangeReplaceableCollection filter(_:)用法及代碼示例
- Swift RangeReplaceableCollection append(_:)用法及代碼示例
- Swift RangeReplaceableCollection +=(_:_:)用法及代碼示例
- Swift RangeReplaceableCollection +(_:_:)用法及代碼示例
- Swift RangeReplaceableCollection init(repeating:count:)用法及代碼示例
- Swift RangeReplaceableCollection insert(contentsOf:at:)用法及代碼示例
- Swift RangeReplaceableCollection append(contentsOf:)用法及代碼示例
- Swift RangeReplaceableCollection用法及代碼示例
- Swift Range clamped(to:)用法及代碼示例
- Swift RangeExpression ~=(_:_:)用法及代碼示例
- Swift Range overlaps(_:)用法及代碼示例
- Swift Range用法及代碼示例
- Swift Range endIndex用法及代碼示例
- Swift Range ~=(_:_:)用法及代碼示例
- Swift RangeExpression relative(to:)用法及代碼示例
- Swift Range isEmpty用法及代碼示例
- Swift Range ==(_:_:)用法及代碼示例
- Swift Range index(_:offsetBy:)用法及代碼示例
- Swift RandomNumberGenerator用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 RangeReplaceableCollection replaceSubrange(_:with:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。