Swift Standard Libraries: Sequence and Collection Functions

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.

advance reference on Swifter

contains

Determines if a SequenceType contains an element

or contains an element that satisfies a predicate

contains reference on Swifter

count

Counts the number of elements in a range

count reference on Swifter

countElements

Counts the number of elements in a CollectionType

countElements reference on Swifter

distance

The distance in elements between two ForwardIndexTypes

distance reference on Swifter

dropFirst

Returns the slice obtained by dropping the first element of a sequence

dropFirst reference on Swifter

dropLast

Returns the slice obtained by dropping the first element of a sequence

dropLast reference on Swifter

enumerate

Prints

enumerate reference on Swifter

equal

Tests two sequences for equality

equal reference on Swifter

extend

Extends a mutable sequence

extend reference on Swifter

filter

Filters a sequence based on a predicate

filter reference on Swifter

first

Returns the first element of a collection

first reference on Swifter

indices

Returns the range of valid indices for a collection

indices reference on Swifter

insert

Inserts a new element into a RangeReplaceableCollectionType

insert reference on Swifter

isEmpty

Returns true if a collection contains no elements

isEmpty reference on Swifter

join

Returns a collection formed by placing a separator between each element of a sequence

join reference on Swifter

last

Returns the last element of a collection (with a BidirectionalIndexType) or nil

last reference on Swifter

lazy

Will be handled in a future post

map

Returns the array generated by applying a function to each element of an array

map reference on Swifter

maxElement

Returns the maximum element of a sequence

maxElement reference on Swifter

minElement

Return the minimum element of a sequence

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

reduce reference on Swifter

removeAll

Remove all elements from a RangeReplaceableCollectionType, optionally requesting the storage capacity be preserved.

removeAll reference on Swifter

removeAtIndex

Remove and return an element from a RangeReplaceableCollectionType

removeAtIndex reference on Swifter

removeLast

Remove and return the last element from a nonempty RangeReplaceableCollectionType

removeLast reference on Swifter

removeRange

Remove elements within a specified index range

removeRange reference on Swifter

reverse

Reverses a CollectionType with an index conforming to BidirectionalIndexType

reverse reference on Swifter

sort

Sorts a mutable collection in place using the < operator or a user supplied comparison function.

sort reference on Swifter

sorted

Returns the Array obtained by sorting a SequenceType using the < operator or a user supplied comparison function.

sorted reference on Swifter

splice

Inserts the elements of a collection into a RangeReplaceableCollectionType at a given index.

splice reference on Swifter

split

split reference on Swifter

startsWith

Determines if the prefix of one SequenceType is equivalent to another SequenceType either using the == operator or a user defined equivalence function

startsWith reference on Swifter

stride

Creates sequences from a given value, to or through a given value, steping by a given increment (or stride).

stride reference on Swifter

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.


Posted in Code Snippets, Swift, Swift Standard Library | Leave a comment

Hardware Review: OWC Aura Pro 480GB SSD Envoy Upgrade Kit for MacBook Air

I love my 11″ MacBook Air. But as a developer, its 120GB SSD has become an issue. With new versions of iOS, beta versions of Xcode and the various Apple programs that don’t play well with external hard drives (I am looking at you iTunes and iPhoto) I seem to be constantly shuffling stuff on and off my G|Drive slim external drive. Finally, exasperated with my new role as a human cache manager, I decided to try to find a solution.

With a quick bit of googling I quickly found the OWC Aura SSD Upgrades page. I chose the 480GB Aura Pro SSD + Envoy + Tools bundle (for $415 plus tax and shipping at time of writing). The Envoy is a case that allows you to use your old SSD as an external drive. The Pro version offers slightly faster write times and a longer warranty than the regular version.

You should be aware that Apple does not view the MacBook Air SSD as a user-upgradable item and what is described in this article may void your warranty.

Update: OWC contacted me to clarify some issues relating to warranties. For more information please see the information provided by Eileen Millard in the comments section below.

Installation

The surprisingly compact Aura Pro Envoy kit. (I though they had left something out!)

The surprisingly compact Aura Pro Envoy kit. (I though they had left something out!)

The Aura Pro Envoy kit comes with everything you need to perform the upgrade: the 480GB SSD, an enclosure to use your old SSD as an external drive, a pouch for the external enclosure, a USB cable, some screws, a user guide and last, but not least, the two special screwdrivers you need to open and close the case of your MacBook Air.

After unpacking all the contents of the kit, I pointed my iPad to an installation video and began.

Contents of the Auro Pro SSD + Envoy + Tools kit.

Contents of the Auro Pro SSD + Envoy + Tools kit.

The screws on the bottom of the MacBook Air are tiny, so it was with some trepidation that I began slowly unscrewing them. I really was afraid I would strip them. I also recommend having a few cups close by to keep the various screws organized.

The installation process went remarkably smoothly and soon the new SSD was in place and I was ready to close up my machine.

View of Installed Aura Pro

View of the installed Auro Pro, just before closing case.

In all the entire procedure took about half an hour, even with my super-slow unscrewing and refastening of the case.

Data Recovery

The instructions link to by the kit recommended a fresh OS install and then a Time Machine restore, a procedure I dutifully followed.

Reinstalling Mavericks

Reinstalling Mavericks

I had been pleasantly surprised at how quickly the hardware upgrade had gone, the data recovery was another matter. It took hours to download and install Mavericks (around 4) and then I started the Time Machine recovery. I ended up letting this process run overnight. I checked on it once and the recovery had completed but it was beginning on its first backup of the new system; it seemed to think everything was new. The following morning I awoke to fully restored machine with lots of free disk space.

Performance

I wanted to make sure that the performance of the upgraded SSD was the same or better than the stock one, so before the upgrade I ran three I/O benchmarks using XBench and I repeated these afterwards. The results can be seen below; the error bars are actually indicating the minimum and maximum data rate measured in each case. Essentially the upgrade performed better or around the same in all but one of the tests โ€“ 256K random writes โ€“ but the difference seemed small and this test was less than rigorous.

SSD Performace Before and After Upgrade

SSD Performace Before and After Upgrade

A Few Weeks Later

I decided not to publish this post until I could post an after note with it, to see if I was still happy with the upgrade a few weeks later and I have to say I am. It really has been great to be able to have multiple versions (5 at the time of writing) of Xcode on my laptop and multiple copies of my projects compiled with each one while trying validate builds and track down any errors. Had I realized the difference it would make I would have done this much sooner.


Posted in Hardware, Review | 1 Comment

Swift Standard Library: Generators, Sequences and Collections

A large part of the Swift Standard Library is concerned with Generators, Sequences and Collections and functions that operate on them, so it’s pretty important to have a good understanding of them.

Generators

A Generator is anything that conforms to the GeneratorType protocol.
It’s fairly simple.

So a generator is simply something that can give you the next element of some sequence of elements. If there is no next element it returns nil.

With this information, we could create a generator, say, of powers of two.

This code conforms to the protocol and is a valid GeneratorType but it is not very easy to use. It will produce an infinite number of elements, without external logic.

For example, to print the first 10 powers we would need to do the following:

We can make it a little easier to use by adding an initializer to set a limit
on how many values we will print.

This version is much easier to use.

OK, so now that we have a generator what can we do with it? Well the answer to
that is… not very much. Very few of the Standard Library Routines take a GeneratorType directly; they require a sequence.

Sequences

A sequence is anything that conforms to the SequenceType protocol. It’s defined as:

Essentially a sequence is a generator factory; something that knows how to make
generators for a sequence.

A first attempt at a power of 2 sequence might look something like this.

As a first attempt this is not bad. This code works and have new capabilities, for example, we can now write:

But there is a problem. It’s easier to see if we move the generator inside the
sequence class.

Hopefully now the problem is plain to see. There is a lot of code repetition here. The two inits are almost identical, the endPower variable is repeated. Surely we can do better? And, of course, we can.

It’s a little subtle what’s going on here, so let’s dig a little deeper. All
the generator logic has been moved into a closure nextClosure.
The closure captures the endPower from the enclosing class and the current
power from the generate function. Finally, the GeneratorOf<T> class is a
Standard Library Class that conforms to GeneratorType and
knows how to use the closure to implement the next method.

Using trailing closure and type inference we can also write this as:

Collections

A collection a sequence that conforms to the CollectionType protocol.
The CollectionType protocol is defined as follows.

So a CollectionType is a SequenceType that can be accessed via a subscript and defines a startIndex and endIndex.

We can upgrade our PowersOfTwoSequence to a Collection with a few small code changes.

While many standard library functions can operate on sequences, some,
for example reverse require an object conforming to CollectionType.

Conclusion

In this post I have examined the three main protocols that Swift uses to underpin many of its functions that operate on sequences and collections and presented example code for each one.

A playground containing all the code from this post is available in the GitHub repository SwiftStandardLibraryPlaygrounds


Posted in Swift, Swift Standard Library, Tutorial | Tagged , , , , | Leave a comment