23 Apr

Swift dates, switches and tuples

DatesInSwift


This app demonstrates a number of iOS techniques in Swift.

You can download the project from Github by clicking this link: DatesInSwift

It uses a date picker to let the user select a date. When the user taps the OK button, it displays a variety of messages depending on the date selected.

Extensions to NSDate


The program includes a file DateExtensions.swift that provides a number of useful utlities for working with dates.

Normally you can’t comare dates using ==, <, <=, >, or >=. The DateExtensions.swift extends NSDate to conform to the Equatable protocol, which allows the == comparison, and the Comparable protocol, which allows <, <=, >, or >= comparisions.

DateExtensions.swift defines a type alias mdyTuple which is a tuple containing the month, day, and year value for a date.

There are utilities that will convert NDate objects back and forth to mdyTuple tuples.

The NSDate instance method mdy() returns an mdyTuple.

The global function date(mdy: mdyTyple) takes an mdyTuple as input and returns an NSDate.

It turns out that you can’t match tuple constants in the cases of a switch statement by default.
In order to do that you have to implement the ~= (pattern match) operator for the tuple type.

For the mdyTuple type, the pattern match function looks like this:

Exploring Swift switch statements


Swift has a very powerful version of the switch statement. You can match strings, you can match ranges of values, and you can match tuples.

The following a valid in Swift:

or

But some of the real power of the Swift Switch statment comes in when you use tuples:

The DatesInSwift demo converts the user-selected date to an mdyTuple, then uses it to demonstrate various types of switch cases.

First, define some constants:

Then do some setup:

And finally the switch statement: