Handling Dates with Swift 3.0

Categories:

Swift 3.0

When you take on a goal as ambitious as the Great Renaming it is a challenge to ensure that all of the reference documentation is updated. As of September 20, 2016, for example, the DateFormatter documentation contains inconsistencies and references to Swift 2.3-style APIs. As time passes this will undoubtedly be corrected, but in the meantime here are a few examples for formatting dates with the Date and DateFormatter.

The current example in the above-reference documentation is:

In Swift 3.0 this changes to:

Notice that .mediumStyle is dropped in favor of .medium. This is in line with simplified naming; we know that the type is of DateFormatter.Style so there is no reason to repeat the word Style. The same applies for .none as opposed to .noStyle.

Now, let’s look at the changes to setting the formatter’s locale:

Again, we see the simplification from Locale(localeIdentifier:) to Locale(identifier:). Less typing and to the point. Likewise the stringFromDate method of the DateFormatter has been streamlined to string(from:), which if you use the entire signature is string(from:Date). See the pattern?

Moving on to creating a Date from a String representation, the Apple documentation has this example:

Applying the principle of reducing verbiage and unnecessary words we arrive at:

The TimeZone initializer drops an extraneous three characters (for), and as expected the dateFromString method becomes date(from:).

Rules of Thumb

It should be apparent that the general rule of thumb when transitioning from Swift 2 to Swift 3 is to remove superfluous words. If you were used to writing formatter.timeStyle = .fullStyle before, get used to writing formatter.timeStyle = .full. If you see someTypeFromAnotherType() it’s likely been replaced with someType(from:AnotherType).

Speaking from experience, after working with Swift 3 for several months now, going back to Swift 2 feels overly verbose, and this is coming from someone who actually likes verbose languages. Once you get the hang of it you’ll be embracing Hemingway and eschewing Tolstoy.

Happy Swifting!

Leave a Reply

Your email address will not be published. Required fields are marked *