Swift Collection Protocols
Swift Collection Protocols
Arrays, Sets and Dictionaries conform to Sequence and Collection, which provide common APIs like count and isEmpty.
Common APIs
Use count and isEmpty to check collection size.
Example
let arr = [1, 2, 3]
print(arr.count)
print(arr.isEmpty)
let s: Set<Int> = [1, 2, 3]
print(s.contains(2))
print(s.isEmpty)
This example shows shared operations exposed via collection protocols.
Indices
Use the indices property to iterate valid positions.
Example
let arr = [10, 20, 30]
for i in arr.indices {
print("index: \(i), value: \(arr[i])")
}