Reputation: 24771
According to the docs:
You can use the insert(:at:), insert(contentsOf:at:), remove(at:), and removeSubrange(:) methods on any type that conforms to the RangeReplaceableCollection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.
However, Set and Dictionary are not listed in the conforming types for RangeReplaceableCollection
.
What gives? This blog suggests they do not conform to it, which makes sense... so is the official Swift Language Guide wrong?
Upvotes: 2
Views: 2044
Reputation: 32870
The documentation link you posted has two references to Dictionary
and Set
:
NOTE
You can use the startIndex and endIndex properties and the index(before:), index(after:), and index(_:offsetBy:) methods on any type that conforms to the Collection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.
, and
NOTE
You can use the insert(:at:), insert(contentsOf:at:), remove(at:), and removeSubrange(:) methods on any type that conforms to the RangeReplaceableCollection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.
I bolded the last part of the two notes, they are identical, it seems this is a copy&paste error. Dictionary
and Set
don't conform to RangeReplaceableCollection
, code that tries to use insert(_:at:)
on those doesn't even compile.
Upvotes: 1
Reputation: 236478
Dictionary
does NOT conform to RangeReplaceableCollection
. You can confirm this with a simple test:
extension RangeReplaceableCollection {
func test() {
print("RangeReplaceableCollection")
}
}
var dictionary: [String: Any] = ["a":1]
var array: [String] = []
array.test() // RangeReplaceableCollection
print(dictionary) // "["a": 1]\n"
dictionary.test() // error: MyPlayground Xcode 12.1.playground:34:12: error: value of type '[String : Any]' has no member 'test'
Regarding the statement about using removeSubrange this is not true. I have no idea why Dictionary is listed there. If you try to use any of those methods it will throw an error:
dictionary.removeSubrange(dictionary.startIndex..<dictionary.endIndex) // // error: MyPlayground Xcode 12.1.playground:14:12: error: value of type '[String : Any]' has no member 'removeSubrange'
If you declare dictionary conformance to it extension Dictionary: RangeReplaceableCollection { }
the compiler will stop complaining but if you try to run the code it will successfully print "RangeReplaceableCollection" but it will hang and them throw an error:
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7ffee60c3fc8). The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
Upvotes: 0