當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift RangeReplaceableCollection用法及代碼示例

協議

RangeReplaceableCollection

支持用另一個集合的元素替換任意子範圍元素的集合。

聲明

protocol RangeReplaceableCollection<Element> : Collection where Self.SubSequence : RangeReplaceableCollection

概述

Range-replaceable 集合提供插入和刪除元素的操作。例如,您可以通過調用 RangeReplaceableCollection 協議定義的任何插入或附加操作將元素添加到字符串數組。


var bugs = ["Aphid", "Damselfly"]
bugs.append("Earwig")
bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1)
print(bugs)
// Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]"

同樣,RangeReplaceableCollection 類型可以使用單個操作刪除一個或多個元素。


bugs.removeLast()
bugs.removeSubrange(1...2)
print(bugs)
// Prints "["Aphid", "Damselfly"]"


bugs.removeAll()
print(bugs)
// Prints "[]"

最後,使用同名的replaceSubrange(_:with:) 方法將元素的子範圍替換為另一個集合的內容。在這裏,整數數組中間的三個元素被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]"

符合RangeReplaceableCollection 協議

要將RangeReplaceableCollection 一致性添加到您的自定義集合,請添加一個空初始化程序和replaceSubrange(_:with:) 方法到您的自定義類型。 RangeReplaceableCollection 使用此初始化程序和方法提供所有其他方法的默認實現。例如,removeSubrange(_:) 方法是通過調用replaceSubrange(_:with:) 來實現的,其中newElements 參數的集合為空。您可以覆蓋任何協議所需的方法來提供您自己的自定義實現。

可用版本

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

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 RangeReplaceableCollection。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。