In the last post in this series, I took at look at the protocols that Swift uses to define generators, sequences and collections. In this post I am going to present examples of using the Standard Library Functions that operate on these types. I’ll run through them in alphabetical order.
Throughout this post I will use “a SequenceType” as a shorthand for “an object conforming to SequenceType protocol” and similar shorthand for other type-like protocols.
I have purposely left out the function definitions. Click on the swifter links to see the gory details. In the playground for the post you can also option-click.
So without further ado let’s get going.
advance
Advances an index by a given number of elements.
1 2 3 |
let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] var seventh = advance(data.startIndex, 6) data[seventh] |
contains
Determines if a SequenceType contains an element
1 2 |
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] contains(data, 7.0) // true |
or contains an element that satisfies a predicate
1 2 3 |
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] let doesContain = contains(data) { x in x > 8.0 } doesContain // true |
count
Counts the number of elements in a range
1 2 |
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] count(data.startIndex..<data.endIndex) // 8 |
countElements
Counts the number of elements in a CollectionType
1 2 |
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] countElements(data) // 8 |
countElements
reference on Swifter
distance
The distance in elements between two ForwardIndexTypes
1 2 |
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] distance(data.startIndex, data.endIndex) // 8 |
dropFirst
Returns the slice obtained by dropping the first element of a sequence
1 2 |
var oneTwoThree = [1,2,3] dropFirst(oneTwoThree) |
dropFirst
reference on Swifter
dropLast
Returns the slice obtained by dropping the first element of a sequence
1 2 |
// var oneTwoThree = [1,2,3] dropFirst(oneTwoThree) |
enumerate
1 2 3 4 5 |
// var oneTwoThree = [1,2,3] println("enumerate") for (pos,value) in enumerate(oneTwoThree) { println("\(pos): \(value)") } |
Prints
1 2 3 |
0: 1 1: 2 2: 3 |
enumerate
reference on Swifter
equal
Tests two sequences for equality
1 2 3 |
// var oneTwoThree = [1,2,3] let fourFive = [4,5] equal(oneTwoThree, fourFive) |
extend
Extends a mutable sequence
1 2 3 |
// var oneTwoThree = [1,2,3] extend(&oneTwoThree, fourFive) oneTwoThree // after [1,2,3,4,5] |
filter
Filters a sequence based on a predicate
1 2 3 |
oneTwoThree // before [1,2,3,4,5] from previous section oneTwoThree = filter(oneTwoThree) { x in x <= 3 } oneTwoThree // after [1,2,3] |
first
Returns the first element of a collection
1 2 3 4 |
// var oneTwoThree = [1,2,3] first(oneTwoThree) // {Some 1} var e = [Int]() first(e) // nil |
indices
Returns the range of valid indices for a collection
1 2 |
// var oneTwoThree = [1,2,3] indices(oneTwoThree) |
insert
Inserts a new element into a RangeReplaceableCollectionType
1 2 3 |
// var oneTwoThree = [1,2,3] var zeroOneTwoThree = oneTwoThree insert(&zeroOneTwoThree, 0, atIndex:0) |
isEmpty
Returns true if a collection contains no elements
1 2 3 4 |
// var zeroOneTwoThree = oneTwoThree isEmpty("") // true isEmpty([Int]()) // true isEmpty(zeroOneTwoThree) // false |
join
Returns a collection formed by placing a separator between each element of a sequence
1 2 |
let relativePathComponents = [ "~", "src", "IDZAQAudioPlayer" ] join("/", relativePathComponents) |
last
Returns the last element of a collection (with a BidirectionalIndexType) or nil
1 2 |
// var oneTwoThree = [1,2,3] last(oneTwoThree) // 3 |
lazy
Will be handled in a future post
map
Returns the array generated by applying a function to each element of an array
1 2 3 |
// var zeroOneTwoThree = [0,1,2,3] var mapResult = map(zeroOneTwoThree) { x in x * x } mapResult // [1,4,9] |
maxElement
Returns the maximum element of a sequence
1 2 |
// var zeroOneTwoThree = [0,1,2,3] maxElement(zeroOneTwoThree) //3 |
maxElement
reference on Swifter
minElement
Return the minimum element of a sequence
1 2 |
// var zeroOneTwoThree = [0,1,2,3] minElement(zeroOneTwoThree) //0 |
minElement
reference on Swifter
prefix
Will be handled in a future post. Operates on a Sliceable.
reduce
Accumulates the result of a function on each element of sequence
1 2 3 4 5 6 7 |
let absolutePathComponents = [ "usr", "local", "bin" ] let path = reduce(absolutePathComponents, "") { accumulate, component in accumulate + "/" + component } path var sum = reduce(oneTwoThree, 0) { a,x in a+x } sum // var oneTwoThree = [1,2,3] reduce(oneTwoThree, 0, +) |
removeAll
Remove all elements from a RangeReplaceableCollectionType, optionally requesting the storage capacity be preserved.
1 2 3 |
// var zeroOneTwoThree = [0,1,2,3] removeAll(&zeroOneTwoThree, keepCapacity: true) zeroOneTwoThree.capacity |
removeAll
reference on Swifter
removeAtIndex
Remove and return an element from a RangeReplaceableCollectionType
1 2 3 |
zeroOneTwoThree = [0,1,2,3] removeAtIndex(&zeroOneTwoThree, 2) //2 zeroOneTwoThree // [0,1,3] |
removeAtIndex
reference on Swifter
removeLast
Remove and return the last element from a nonempty RangeReplaceableCollectionType
1 2 |
zeroOneTwoThree = [0,1,2,3] removeLast(&zeroOneTwoThree) |
removeLast
reference on Swifter
removeRange
Remove elements within a specified index range
1 2 |
zeroOneTwoThree = [0,1,2,3] removeRange(&zeroOneTwoThree, 1...2) |
removeRange
reference on Swifter
reverse
Reverses a CollectionType with an index conforming to BidirectionalIndexType
1 2 |
zeroOneTwoThree = [0,1,2,3] var threeTwoOneZero = reverse(zeroOneTwoThree) |
sort
Sorts a mutable collection in place using the < operator or a user supplied comparison function.
1 2 3 4 |
threeTwoOneZero // [3,2,1,0] sort(&threeTwoOneZero) threeTwoOneZero // [0,1,2,3] sort(&threeTwoOneZero) { x,y in x>y } |
sorted
Returns the Array obtained by sorting a SequenceType using the < operator or a user supplied comparison function.
1 2 3 4 |
let random = [1,6,2,8,3,3,2,8,7] let randomSortedAscending = sorted(random) let randomSortedDescending = sorted(random) { x,y in x>y } randomSortedDescending |
splice
Inserts the elements of a collection into a RangeReplaceableCollectionType at a given index.
1 2 3 |
var gap = [0,1,2,7,8,9] var missing = [3,4,5,6] splice(&gap, missing, atIndex:3) |
split
1 2 3 4 5 |
let pathToSplit = "/usr/local/bin" var splitPath = split(path) { c in c == "/" } splitPath splitPath = split(path, { c in c == "/" }, maxSplit:2, allowEmptySlices:true) splitPath |
startsWith
Determines if the prefix of one SequenceType is equivalent to another SequenceType either using the == operator or a user defined equivalence function
1 2 3 4 5 6 7 8 |
let oneToFive = [1,2,3,4,5] let oneToThree = [1,2,3] startsWith(oneToFive, oneToThree) let floats125 = [1.0,2.0,3.0,4.0,5.0] let fuzzyPrefix = [1.01,1.99,3.01] let isFuzzyPrefix = startsWith(floats125, fuzzyPrefix) { x,y in abs(x-y) < 0.02 } isFuzzyPrefix |
startsWith
reference on Swifter
stride
Creates sequences from a given value, to or through a given value, steping by a given increment (or stride).
1 2 3 4 |
let to = stride(from:0, to:100, by:10) map(to) { x in println(x) } let through = stride(from:0, through:100, by:10) map(through) { x in println(x) } |
underestimateCount
Will be covered in a future post.
Download the Playground
The playground for this, and all other posts in the series, can be found on GitHub in the SwiftStandardLibraryPlaygrounds repository.