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 {swift}SequenceType{/swift}” as a shorthand for “an object conforming to {swift}SequenceType{/swift} 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.
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 {swift}SequenceType{/swift} contains an element
// 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
// 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
// let data = [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0] count(data.startIndex..<data.endIndex) // 8 [/swift] <a href="http://swifter.natecook.com/func/count"><code>count</code> reference on Swifter</a> <h2>countElements</h2> Counts the number of elements in a {swift}CollectionType{/swift} [swift] // 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 {swift}ForwardIndexTypes{/swift}
// 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
var oneTwoThree = [1,2,3] dropFirst(oneTwoThree)
dropFirst
reference on Swifter
dropLast
Returns the slice obtained by dropping the first element of a sequence
// var oneTwoThree = [1,2,3] dropFirst(oneTwoThree)
enumerate
// var oneTwoThree = [1,2,3] println("enumerate") for (pos,value) in enumerate(oneTwoThree) { println("\(pos): \(value)") }
Prints
[default]
0: 1
1: 2
2: 3
[/default]
enumerate
reference on Swifter
equal
Tests two sequences for equality
// var oneTwoThree = [1,2,3] let fourFive = [4,5] equal(oneTwoThree, fourFive)
extend
Extends a mutable sequence
// var oneTwoThree = [1,2,3] extend(&oneTwoThree, fourFive) oneTwoThree // after [1,2,3,4,5]
filter
Filters a sequence based on a predicate
oneTwoThree // before [1,2,3,4,5] from previous section oneTwoThree = filter(oneTwoThree) { x in x <= 3 } oneTwoThree // after [1,2,3] [/swift] <a href="http://swifter.natecook.com/func/filter"><code>filter</code> reference on Swifter</a> <h2>first</h2> Returns the first element of a collection [swift] // 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
// var oneTwoThree = [1,2,3] indices(oneTwoThree)
insert
Inserts a new element into a {swift}RangeReplaceableCollectionType{/swift}
// var oneTwoThree = [1,2,3] var zeroOneTwoThree = oneTwoThree insert(&zeroOneTwoThree, 0, atIndex:0)
isEmpty
Returns true if a collection contains no elements
// 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
let relativePathComponents = [ "~", "src", "IDZAQAudioPlayer" ] join("/", relativePathComponents)
last
Returns the last element of a collection (with a BidirectionalIndexType) or nil
// 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
// 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
// var zeroOneTwoThree = [0,1,2,3] maxElement(zeroOneTwoThree) //3
maxElement
reference on Swifter
minElement
Return the minimum element of a sequence
// 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
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 {swift}RangeReplaceableCollectionType{/swift}, optionally requesting the storage capacity be preserved.
// var zeroOneTwoThree = [0,1,2,3] removeAll(&zeroOneTwoThree, keepCapacity: true) zeroOneTwoThree.capacity
removeAll
reference on Swifter
removeAtIndex
Remove and return an element from a {swift}RangeReplaceableCollectionType{/swift}
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 {swift}RangeReplaceableCollectionType{/swift}
zeroOneTwoThree = [0,1,2,3] removeLast(&zeroOneTwoThree)
removeLast
reference on Swifter
removeRange
Remove elements within a specified index range
zeroOneTwoThree = [0,1,2,3] removeRange(&zeroOneTwoThree, 1...2)
removeRange
reference on Swifter
reverse
Reverses a {swift}CollectionType{/swift} with an index conforming to {swift}BidirectionalIndexType{/swift}
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.
[swift]
threeTwoOneZero // [3,2,1,0]
sort(&threeTwoOneZero)
threeTwoOneZero // [0,1,2,3]
sort(&threeTwoOneZero) { x,y in x>y }
[/swift]
sort
reference on Swifter
sorted
Returns the {swift}Array{/swift} obtained by sorting a {swift}SequenceType{/swift} using the < operator or a user supplied comparison function.
[swift]
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
[/swift]
sorted
reference on Swifter
splice
Inserts the elements of a collection into a {swift}RangeReplaceableCollectionType{/swift} at a given index.
var gap = [0,1,2,7,8,9] var missing = [3,4,5,6] splice(&gap, missing, atIndex:3)
split
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 {swift}SequenceType{/swift} is equivalent to another {swift}SequenceType{/swift} either using the == operator or a user defined equivalence function
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 [/swift] <a href="http://swifter.natecook.com/func/startsWith"><code>startsWith</code> reference on Swifter</a> <h2>stride</h2> Creates sequences from a given value, to or through a given value, steping by a given increment (or stride). [swift] 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.