August 2016

Yup.

by Joey deVilla on August 31, 2016

most used language in programming

{ 0 comments }

In this article, we’ll expand on material covered in the three previous articles in this series:

A more readable way to work with Dates and DateComponents

Suppose we want to find out what the date and time will be 2 months, 3 days, 4 hours, 5 minutes, and 6 seconds from now will be. If you recall what we covered in the last installment in this series, you’d probably use code like this:

In the code above, we did the following:

  • We created an instance of a DateComponents struct.
  • We set its properties so that it would represent a time interval of 2 months, 3 days, 4 hours, 5 minutes, and 6 seconds.
  • We then used Calendar‘s date(byAdding:to:) method to add the time interval to a Date.

This code wouldn’t look out of place in a lot of other programming languages, but we can do better in Swift. What if I told you that by defining a few helper functions, you can turn the code above into the code below?

Or this code?

I’d much rather write the code above. This article will cover the code necessary to make this kind of syntactic magic possible.

Overloading + and - so that we can add and subtract DateComponents

First, let’s write some code that allows us to add and subtract DateComponents. Start a new playground and enter the following code into it:

In the code above, we’ve overloaded the + and – operators so that we can add and subtract DateComponents. I derived these functions from Axel Schlueter’s SwiftDateTimeExtensions library. He wrote them when Swift was still in beta; I updated them so that they compile with the current version and added a couple of tweaks of my own.

The addition and subtraction operations are so similar and so tedious, which is a sign that there’s an opportunity to DRY up the code. I factored out the duplicate code from both the + and - overloads and put it into its own method, combineComponents, which does the actual DateComponents addition and subtraction.

You may have noticed a lot of ?? operators in the code for combineComponents. ?? is referred to as the nil coalescing operator, and it’s a clever bit of syntactic shorthand. For the expression below:

let finalValue = someOptionalValue ?? fallbackValue

  • If someOptionalValue is not nil, finalValue is set to someOptionalValue‘s value.
  • If someOptionalValue is nil, finalValue is set to fallbackValue‘s value.

Let’s confirm that our code works. Try out the following code:

Overloading - so that we can negate DateComponents

Now that we can add and subtract DateComponents, let’s overload the unary minus so that we can negate DateComponents:

With this overload defined, we can now use the unary minus to negate DateComponents:

Overloading + and - so that we can add Dates and DateComponents and subtract DateComponents from Dates

With the unary minus defined, we can now define the following operations:

  • Date + DateComponents
  • DateComponents + Date
  • DateDateComponents

Note that we didn’t define an overload for subtracting Date from DateComponents — such an operation doesn’t make any sense.

With these overloads defined, a lot of Date/DateComponents arithmetic in Swift becomes much easier to enter and read:

Extending Date so that creating dates is simpler

Creating Dates in Swift is a roundabout process. Usually, you end up creating them in one of two ways:

  • Instantiating a DateComponents struct and then using it to create a Date using Calendar‘s date(from:) method, or
  • Creating a String representation of the Date and then using it to create a Date using DateFormatter‘s date(from:) method.

Let’s simplify things by extending the Date struct with a couple of convenient init method overloads:

With these methods, initializing Dates is a lot more simple:

Overloading - so that we can use it to find the difference between two Dates

When we’re trying to determine the time between two given Dates, what we’re doing is finding the difference between them. Wouldn’t it be nice if we could use the - operator to find the difference between Dates, just as we can use it to find the difference between numbers?

Let’s code an overload to do just that:

Let’s test it in action:

Extending Int to add some syntactic magic to date components

We’ve already got some syntactic niceties, but the real Swift magic happens when we add this code to the mix:

This additions to Int allow us to convert Ints to DateComponents in an easy-to-read way, and with our overloads to add and subtract DateComponents to and from each other, and to add Dates to DateComponents, we can now perform all sorts of syntactic magic like this:

Extending DateComponents to add even more syntactic magic: fromNow and ago

And finally, a couple of additions to the DateComponents struct to make Date/DateComponent calculations even more concise and readable:

Here are these additions in action:

Wrapping it all up

Here’s the playground containing all the code we just worked with:

 

{ 6 comments }

abacus with toy clock

You can actually buy this thing on Etsy! Click the photo for details.

What we’ve covered so far, and what we’ll cover in this installment

So far, in this series on date and time programming in Swift 3, we’ve looked at:

With this knowledge under our belts, let’s get to this article’s topic: doing date calculations.

Creating a couple of Dates to work with

stevenotes

Let’s create a couple of Dates to work with:

  • The date and time of the Stevenote where the iPhone was introduced: January 9, 2007, 10:00 a.m. Pacific time (UTC-8), and
  • The date and time of the Stevenote where the iPad was introduced: January 27, 2010, 10:00 a.m. Pacific time (UTC-8).

Start with a fresh playground, and paste or enter the following code into it:

In the code above, we’ve created our dates in two different ways:

  • We created iPhoneStevenoteDate by setting up a DateComponents struct and then using the user’s Calendar to convert those DateComponents into a Date.
  • We created iPadStevenoteDate by converting its String representation into a Date using a DateFormatter. You may find that if you need to instantiate a large number of Dates in code, you may want to do so this way, since this approach requires far fewer lines of code than doing so using DateComponents.

Date comparisons, part 1

A chick looking at an egg.

Now that we have two Dates, let’s compare them. In Swift 3, we can use familiar comparison operators — <, <=, ==, !=, >, >== — to tell which Date came first, or if they represent the same point in time.

Add the following code to the playground:

Note that these are comparisons of Dates, which measure time down to the nearest nanosecond. If you compare two Dates named date1 and date2, where date2 represents a point in time one nanosecond after date1, they will not be equal; date2 will be greater than date1.

A little later on in this article, we’ll look at more “human” ways of comparing Dates.

How far apart are the iPhone and iPad Stevenotes, part 1: In seconds, using Date’s timeIntervalSince method

Date‘s timeIntervalSince method can give us the difference between two dates and times — in seconds. Add the following code to the playground:

The results tell us that there were 96,248,600 seconds between the iPhone Stevenote and the iPad Stevenote.

While there are cases when you’ll want to know how many seconds there are between two given points in time, there are also many cases where you’ll want to find the differences between two points in time using other units, such as days, weeks, months, and years, not to mention hours and minutes.  Date‘s timeIntervalSince method isn’t going to work for these cases.

How far apart are the iPhone and iPad Stevenotes, part 2: In days, using Calendar’s dateComponents(_:from:to:) method

Most of the time, when you are calculating how far apart two given Dates are, you’ll be using this method of the Calendar struct:

dateComponents(components, from: startDate, to: endDate)

Here’s a run-down of its parameters:

Parameter Description
components Set (expressed in array notation) of Calendar.Component values specifying the time units you want, which can be:

  • .second
  • .minute
  • .hour
  • .day
  • .month
  • .year
startDate .orderedSame
endDate .orderedAscending

Let’s use dateComponents(_:from:to:) to find out how many days there were between the iPhone Stevenote and the iPad Stevenote. Add the following code to the playground:

In the code above, we passed dateComponents(_:from:to:) three values:

  • An array containing the Calendar.Component value .day, which specifies that we want the result expressed as the difference between iPadStevenoteDate and iPhoneStevenoteDate in terms of days.
  • The two dates in question, iPhoneStevenoteDate and iPadStevenoteDate.

As the result tells us, there were 1,114 days between the iPhone Stevenote and the iPad Stevenote.

How far apart are the iPhone and iPad Stevenotes, part 3: In weeks

By changing the contents of the array of Calendar.Component values that we provide in the first argument of Calendar’s dateComponents(components, from: startDate, to: endDate) method, we can get the result expressed in different time units. Add the following code to the playground:

In the code above, we passed dateComponents(_:from:to:) three values:

  • An array containing the Calendar.Component value .weekOfYear, which specifies that we want the result expressed as the difference between iPadStevenoteDate and iPhoneStevenoteDate in terms of the numbered weeks of the year on which both dates fall. For example, if event1 took place on week 2 of a year and event2 took place on week 5, the difference between the two in .weekOfYear terms would be 3.
  • The two dates in question, iPhoneStevenoteDate and iPadStevenoteDate.

The result indicates that 159 weeks passed between the iPhone Stevenote and the iPad Stevenote.

If you do the math, 159 times 7 days is 1,113 days, but our previous calculation said that the iPhone Stevenote and the iPad Stevenote were 1,114 days apart. That’s because the two events are 159 whole weeks apart, plus an extra day.

How far apart are the iPhone and iPad Stevenotes, part 4: In years, months, and days

We can also put multiple values of Calendar.Component into the array that we provide as the first argument of Calendar’s dateComponents(components, from: startDate, to: endDate) method. Add the following code to the playground:

In the code above, we passed dateComponents(_:from:to:) three values:

  • An array containing the Calendar.Component values .year, .month, .day, .hour, .minute, which specifies that we want the result expressed as the difference between iPadStevenoteDate and iPhoneStevenoteDate in terms of years, months, days, hours, and minutes. The method uses the largest applicable component before using smaller ones — for example, it will give results like 1 month and 5 days rather than 35 days.
  • The two dates in question, iPhoneStevenoteDate and iPadStevenoteDate.

The results show that the iPhone Stevenote and the iPad Stevenote were 3 years and 18 days apart.

Date addition, part 1: What’s the last day of a 90-day warranty that starts today?

90-day-warranty

Now that we know how to answer the question “What’s the difference in time between two Dates?”, let’s try answering a different question: “If we add a time interval to a Date, what’s the resulting Date?”

To answer this question, we’ll use this method of the Calendar struct:

date(byAdding: timeUnit, value: numberOfTimeUnits to: startDate)

Here’s a run-down of its parameters:

Parameter Description
timeInterval dateComponents struct whose properties contain values defining the interval of time.
numberOfTimeUnits The number of timeInterval units to be added to the Date in question.
startDate The Date in question.

Let’s start with a simple bit of code that tells us the last day of a 90-day warranty whose term starts right now:

The result is a Date representing a point in time 90 days from the present.

Date addition, part 2: What was the date 5 weeks ago?

Just as we can convert addition to subtraction by adding a negative value, we can also do Date subtraction by providing date(byAdding:value:to:) with negative values. Here’s an example of code that returns a date that is an interval of time prior to the date in question:

The result is a Date representing a point in time 5 weeks in the past.

Date addition, part 3: What time will it be 4 hours and 30 minutes from now, and 4 hours and 30 minutes ago?

The date(byAdding:value:to:) method works when you just want to add one kind of time unit — a minute, hour, day, week, month, or year — to a Date. If you want to add multiple kinds of time units to a Date, such as 4 hours and 30 minutes, you need to use this Calendar method instead:

date(byAdding: timeIntervalComponents, to: startDate)

Here’s a run-down of its parameters:

Parameter Description
timeInterval dateComponents struct whose properties contain values defining the interval of time.
startDate The Date in question.

Here’s the code that answers the question “What time will it be 4 hours and 30 minutes from now?”

In the code above, we did the following:

  • First, we defined a DateComponents struct representing a 4-hour, 30-minute span of time,
  • then we added that span of time to the present date and time using the date(byAdding:to:) method.

The result is a Date representing a time 4 hours and 30 seconds in the future.

Let’s find out what the Date was 4 hours and 30 seconds ago:

Date comparisons, part 2: Making Date comparisons a little more “human”

One recurring theme in science fiction (and especially in Star Trek) is the tendency for ultra-smart characters and computers to be overly, needlessly, pointlessly precise. The writers for the original series often did this with Spock, and it seemed that at least a few writers were aware of this annoying trope in later series. Here’s a bit of dialogue from The Next Generation:

Data: 6 days, 13 hours, 47 minutes.
Riker: What, no seconds?
Data: I have discovered, sir, a certain level of impatience when I calculate a lengthy time interval to the nearest second. [beat] However if you wish…
Riker: No. No. Minutes is fine.

Date‘s comparison operators have the same problem with being overly precise. Consider the following Dates:

  • The start of the iPhone Stevenote: January 9, 2007, 10:00:00 a.m. PST
  • One second after the start of the iPhone Stevenote: January 9, 2007, 10:00:01 a.m. PST
  • Five minutes after the start of the iPhone Stevenote: January 9, 2007, 10:05:00 a.m. PST
  • Three hours after the start of the iPhone Stevenote: January 9, 2007, 1:00:00 p.m. PST

Date‘s comparison operators think of all these points in time as very different, but depending on your circumstances you may think of them as being practically the same:

  • In most cases, there really isn’t a difference between the time when the iPhone Stevenote and one second after.
  • If you’re concerned only with the day on which the iPhone Stevenote took place and not the exact time, there’s effectively no difference between any of the Dates listed above.

Calendar‘s compare(_:to:toGranularity) method allows us to perform Date comparisons at different levels of granularity:

compare(firstDate, to: secondDate, toGranularity: granularity)

Here’s a run-down of its parameters:

Parameter Description
firstDate The first Date in the comparison.
secondDate The second Date in the comparison.
granularity The level of precision for the comparison, expressed as an Calendar.Component value, which includes:

  • .second
  • .minute
  • .hour
  • .day
  • .month
  • .year

This is a Cocoa method named “compare”, so you’ve probably guessed that its return type is ComparisonResult. Here’s what it returns:

If… compare returns:
firstDate is earlier than secondDate, when compared at the specified level of precision .orderedAscending
firstDate is equal to secondDate, when compared at the specified level of precision .orderedSame
firstDate is later than secondDate, when compared at the specified level of precision .orderedAscending

It’s easier to show compare(_:to:toGranularity) in action than to explain how it works. Add the following code into the playground:

Wrapping it all up

Here’s the playground containing all the code we just worked with:

In the next installment, we’ll look at making working with dates and times more Swift-like.

{ 2 comments }

whisky bacon emoji

…namely, Whisk(e)y and bacon. Now my communications needs have been met — I just have to wait for the over-the-air update to come out for my Moto G4.

{ 0 comments }

swift dateformatter class

Click the diagram to see it at full size.

In the previous article in this series, we looked at three key structs for date and time programming in Swift:

  • Date represents a single point in time, using a format that can easily be translated into just about any calendar and time-reckoning system: a number of seconds relative to the start of the Third Millennium (January 1, 2001, 00:00:00 UTC).
  • DateComponents specifies time units like year, month, day, hour, minute, and more to represent either a point in time or a duration of time.
  • Calendar provides a context for Dates, and converts Dates to DateComponents and DateComponents to Dates.

These structs all deal with the internal representation of dates and times. In this article, we’ll look at the DateFormatter class, which allows us to deal with their external representation — by converting Dates into Strings, and properly-formatted Strings into Dates.

Let’s convert a Date into a String, part 1: Just the date

alexander graham bell and phone

Start a new playground and enter the following code, which gives us a Date that we can format — the day when Alexander Graham Bell made the very first phone call:

Now let’s try turning this date into a string with a DateFormatter:

You may be surprised that the result is an empty String. This can be fixed by specifying a dateStyle:

Let’s try the other dateStyles:

Why would there be a dateStyle called .none? I’ll explain in a little bit.

Let’s convert a Date into a String, part 2: A date and a time

steve jobs and ipad

Let’s work with an event for which we know both the date and time: the “Stevenote” where the iPad was introduced, which started on January 27, 2010, at 10:00 a.m. Pacific Time (UTC-8). We’ll define this as a Date by adding the following code:

Now that we have a date and time, let’s format it using the dateStyle and timeStyle properties:

Now that we’re working with a date and time, let’s see what the .none style is for:

Remember that in Swift, the Date struct represents a single point in time, which has both a date and a time. The .none style for DateFormatter‘s dateStyle and timeStyle properties allows us to create a String representation of a Date that shows only its date or time part.

Let’s convert a Date into a String, part 3: Custom date/time formats

electronic calendar

Before we begin working with custom date/time formats, I should point out that if you need to display a Date as a String to the user, it’s best if you use Swift’s built-in dateStyle and timeStyle values. They display dates and times properly, according to the user’s settings, which include country and language. You’d be surprised how date formats differ from culture to culture, and it’s better to let Swift do the formatting work.

However, there are times when you need to format dates and times in a specific way that doesn’t match the styles provided by DateFormatter‘s dateStyle and timeStyle properties, such as when dealing with certain APIs. That’s where DateFormatter‘s dateFormat property comes in handy:

You can use the date format specifiers listed in Appendix F of the Unicode Technical Standard #35 to define the formatting String for the dateFormat property. Here are some examples:

Let’s convert a String into a Date

clock and calendar

DateFormatter works the other way — just as it can convert Dates to Strings, it can also convert Strings to Dates. By setting its dateFormat to the format of the String it should expect, you can use its date(from:) method to convert a String into a Date:

Let’s change the dateFormat string and try it again:

Wrapping it all up

Here’s a playground containing all the code we just worked with:

In the next installment, we’ll look at date calculations.

{ 7 comments }

Pokémon Go and workplace data security

pokemon go

With over 25 million users playing every day, and downloads and active users surpassing even Twitter and Tinder, Pokémon Go is turning out to be one of the most popular mobile applications of all time. According to Data Security Law Blog, it also highlights the risks in BYOD (Bring Your Own Device) policies.

With a BYOD device that has Pokémon Go installed, the risks come from the security — or more accurately, insecurity — of the Pokémon Go app itself. Earlier versions of the game gave the app full access to the user’s complete Google account profile and related information, including Google-accessible email accounts and search history. While it’s not likely that this now-fixed security hole led to any breaches, it’s a prime example of how a suddenly popular app running on a BYOD device can lead to trouble.

All this is still new territory — the smartphone as we currently know it won’t even turn 10 until next year — and businesses would do well to watch the effects of apps like Pokémon Go, and alter their mobile policies accordingly.

The pros and cons of BYOD

byod

As we’ve observed before, mobile devices are more personal than even “personal” computers. People don’t want to part with them, which is why they prefer to bring them to work — and use them for work. This attachment to our mobile devices, for which we’re finding more and more uses, is why at least two-thirds of employees are using their own mobile devices in the course of doing their jobs.

Tech.co has a brief but useful article that summarizes the big pros and cons of BYOD, explains what the general best practices are, and explains why training employees is key to a successful BYOD implementation. If your organization is considering or just starting with a BYOD program, it would be worth your time to read this article.

The 11-step guide to BYOD security, or how to avoid getting fired

security

In a recent entry on their blog, Heimdal Security provide these BYOD statistics:

In the same article, they list eleven common sense (which is uncommon) steps for BYOD users to secure the personal mobile devices they use for work. As they say, “security is each user’s own business”.

this article also appears in the GSG blog

{ 0 comments }

The next Tampa iOS Meetup, and upcoming changes

by Joey deVilla on August 19, 2016

change

It’s been a couple of months since the last Tampa iOS Meetup, and with summer drawing to a close and iOS 10 coming very soon, it’s time to kick things back into high gear. It’s going to be an interesting fall, what with the coming changes…

bay to bay

angelaThe first change is that Angela, who originally put this Meetup group together, landed a job in San Francisco and moved there. I want to congratulate her on seizing this opportunity — I did the same thing during the dot-com bubble of the late ’90s — and wish her the very best in her adventures in the other Bay Area. I’d also like to thank her for all the work she’s done for this Meetup group, which wouldn’t even exist without the initial spark that she provided.

As for me, I plan to stick around, and will continue in my role as this Meetup group’s organizer, lead speaker, and accordion player.

building imessage sticker packs and messaging apps for ios 10

The next change comes from Apple, in the form of iOS 10, Xcode 8, and Swift 3, and we’ll be talking about what these new versions mean for you as iOS developers over the next couple of meetups.

The date for the next meetup is to be determined, but I’m aiming for early September, and the topic will be Building iMessage sticker packs and messaging apps for iOS 10. iMessage is one of the most-used iOS apps, and a lot of people seem to like adding a little flair to their communications, so the introduction of sticker packs and iMessage apps represents an opportunity for the developer looking to make a splash. Sticker packs have the added bonus of not needed any programming to develop.

samsung galaxy s7 and iphone 6s

The final change is one that I’d like your opinion on. I’m thinking of expanding the subject area of our Meetup group to cover these topics:

  • iOS development, which it already covers,
  • Android development,
  • and IoT (internet of things) development

In other words, I’m thinking about expanding our group’s coverage to while I like calling development for “Tiny shiny platforms”. Would this be something that you’d be interested in, or would you rather stick to just iOS? I’d love to hear what you think — let me know by dropping me a line at joey@joeydevilla.com­!

{ 0 comments }