What’s new Swift 4.2?

The latest update of Swift 4.2 came out last week at WWDC, and it has some pretty exciting improvements.

Some had me thinking ‘that’ll be useful’, some had me excited and some, to be honest, had me thinking ‘FINALLY!’ Here are some of my highlights:

Random

giphy.gif

One feature that I’m especially pleased about is random. Random has always been a sticking point for me in Swift – arc4random, arc4random_uniform, and drand48  have seemed out of place – more like an artifact from ancient history than a part of a ‘modern’ language, and in fact, they were! These methods directly accessed lower level C APIs.

arc4random and arc4random_uniform used and returned the little used UInt32 type (Int and UInt are much more common in Swift, which automatically uses either the 32 or 64 bit version depending on the platform your app is running on.) This means that the parameter being passed and the response always had to be converted, making a request for random extra verbose. Want a random integer between 0 and 10? Take a look at this:

let max = 10
//pre Swift 4.2
let result = Int(arc4random_uniform(UInt32(max)))

Wow. See what I mean? And if the laborious syntax isn’t a convincing enough reason – arc4random didn’t return uniform distribution of random numbers, drand48 (though it did return more useful data type Double) required an additional step of seeding, and let’s be honest – these methods had horribly ugly names!

Well – breathe a sigh of relief because Swift 4.2 has a new and exciting API with a whole range of convenience methods to make our lives easier as developers.

Remember the random integer between 0 and 10? How about this:

let max = 10
//Swift 4.2
let result = Int.random (in: 0 ..< max)

Much simpler and more readable, right? And it doesn’t have to be an integer, all numeric types have a random method now – here’s the Double version:

let max = 10
//Swift 4.2
let result = Double.random (in: 0 ..< max)

There are even collection convenience methods that select a random element.
Want to pick a suit, any suit? Too easy now:

var suits = ["Hearts","Diamonds","Clubs","Spades"]
//Swift 4.2
let suit = suits.randomElement()!

Want to shuffle the suits? Just as easy:

//Swift 4.2
suits.shuffle()

You can check out the Swift Evolution proposal for random unification here.

Bool toggle

Speaking of neat little convenience methods, here’s another!

You can now simply call the toggle method on a boolean.

No more:

//pre Swift 4.2
soundOn = !soundOn

You can now do this:

//Swift 4.2
soundOn.toggle()

You can check out the Swift Evolution proposal for adding toggle to Bool here.

New Collection higher order functions

When higher order functions come up, people often discuss the big four – map, filter, reduce and sort. In my post on higher order functions in Swift, I looked at a whole bunch of other higher order functions that collection types offer. Well, in Swift 4.2 we have more!

allSatisfy

Whereas the contains method returns a Bool based on whether at least one element in a collection satisfies a condition, the new allSatisfy method returns a Bool based on whether all elements satisfy a condition. For example:

var fruits = ["Banana","Banana","Coconut","Banana","Banana","Banana"]
//Swift 4.2
let completelyBananas = fruits.allSatisfy { $0 == "Banana" } //false

Check out the SE proposal here.

First and last

We previously had methods index(of:) and index(where:) which found the first item which satisfied a condition. We now have lastIndex(of:) and lastIndex(where:) too, which finds the last item in the collection that satisfies a condition. It made sense then to change the name of the index methods to firstIndex(of:) and firstIndex(where:).

You can find the SE proposal for first and last methods here.

Remove all

Remember the confusion you had when you first tried to remove all items from an array that satisfied a condition using a simple for loop?
You may have programmed something like:

var fruits = ["Banana","Banana","Coconut","Banana","Banana"]
//remove all bananas (naive implementation)
for (index,fruit) in fruits.enumerated() {
  if fruit == "Banana" {
    fruits.remove(at: index)
  }
}

Then everything really did go bananas when an Index out of Range error appeared in the console?

Oopsbutton.jpg

Ah for more innocent days.

Of course the index had continued to increment while the number of elements in the array steadily decreased, until finally the loop index was higher than the number of elements in the array, causing a crash. There were solutions to this problem of course – loop in reverse, for example, or use the filter method, but now we have a method built for just this task, removeAll. Take a look:

var fruits = ["Banana","Banana","Coconut","Banana","Banana"]
//remove all bananas (Swift 4.2)
fruits.removeAll { $0 == "Banana" }

Well,​ that was easier! You can find the SE proposal for remove all collection method here.

Looping through enumerations

I remember years ago having an enumeration nicely set up – I think it was something like an enum for card suits…

enum Suit {
  case hearts
  case diamonds
  case clubs
  case spades
}

…and I remember realizing I needed to loop through the cards. (Perhaps it was to find a random suit) I remember thinking – well that shouldn’t be so hard, I already have the enum set up, right?

I then realized that this isn’t a default feature of enums, and I remember thinking, “whaaa?”

Pp9rx.gif

Of course,​ there was a way around this – you could set up a static variable for example that contained an array of all the items in the enum:

//pre Swift 4.2
enum Suit {
  case hearts
  case diamonds
  case clubs
  case spades
  static var allCases:[Suit] = [.hearts, .diamonds, .clubs, .spades]
}

You could then use this allCases property to loop through the cases:

for suit in Suit.allCases {
  print(suit)
}

Well, Swift 4.2 (FINALLY!) can automatically synthesize this for you. All you need to do is adopt the CaseIterable protocol.

//Swift 4.2
enum Suit:CaseIterable {
  case hearts
  case diamonds
  case clubs
  case spades
}

Imagine – combined with the new collection convenience methods, we could now shuffle your enum case suits:

//Swift 4.2
var suitsShuffled = Suit.allCases.shuffled()

Or pick a random suit!

//Swift 4.2
var pickASuitAnySuit = Suit.allCases.randomElement()!

Wow! You can find the SE proposal for the all cases property for enums here.

Well – that’s plenty to be excited about with Swift 4.2, and I haven’t even covered everything new! If you’re interested in reading about other proposals I haven’t mentioned that made it into Swift 4.2 or perhaps are on their way for Swift 5, you can take a look over at the Swift Evolution page.

Tagged with: , , , ,
Posted in Swift

Check out my livevideo course “iOS Development with Swift in Motion”!

I’d love for you to check out my video course “iOS Development with Swift in Motion”.

 

The course is out on Manning’s livevideo platform, and if you get in early with Manning’s early access program you can get 40% off with code ytgrummitt at manning.com.

See you in the videos!

 

Posted in Swift

Block comments, key bindings and feeling foolish!

Do you ever get stuck on something, and then when you work out what you were doing wrong you feel a bit foolish?

I was just thinking – it would be much more convenient if there was a keyboard shortcut to block comment some code. I know that with the keyboard shortcut Command-/ you can automatically generate single line comments:

BlockComment3.gif

But what I was after was a keyboard shortcut to generate block comments. Strangely this capability seems to be missing from Xcode, but I happened upon an Xcode Source Editor extension called BlockComment that seemed to do the job.

So – after installing BlockComment, I went into the Key Bindings tab in Xcode preferences, double clicked on the BlockComment binding to add a keyboard shortcut, and… nothing.BlockComment1.gif

I closed Xcode, opened Xcode – did it again and… nothing. I’ve done this before, how strange! Read up on key bindings, hmm… yes I seem to be doing the right thing, what could be going wrong?

Then I watched a video and that was when I felt foolish.

Of course! You can’t just click anywhere on the line – you need to click in the key field on the right!

BlockComment2.gif

Sometimes when you work out what you were doing wrong, it all seems so obvious!

So! Things I’ve learned today

FIRST – When customizing a keyboard shortcut in Key bindings – click in the Key field!

SECONDBlockComment – works quite well, I recommend!

BlockComment4.gif

THIRD – sometimes there’s no substitute for a video tutorial!

You might think that’s a strange sentiment for a book author, but as it turns out I’m currently working on a video course to accompany the book!

Of course, everyone has a preference for how to learn. Maybe you like books coz you can read them on the train. Maybe you prefer videos as you find it easier to learn visually. Either way, you have a choice now when learning iOS development with Swift.

Combo.jpg

You can check out the book “iOS Development with Swift” here.

Or – you can check out the livevideo course “iOS Development with Swift in Motion” here. The video course is currently in the Manning early access program, and new Units will be put out regularly.

You can use both together or independently, depending on your preference!

Good luck with them, and enjoy block commenting your code with keyboard shortcuts!

Tagged with: ,
Posted in Swift

Learn iOS and Swift – interactive video course

Exciting news! For most of this year I’ve been busy working on a series of video tutorials in iOS and Swift, and this week we’re launching the Manning Early Access Program(MEAP) for the course.

There will be 13 units in total – with approximately half an hour per unit that should be hours and hours of quality content to get you up and going in iOS and Swift.

You can check out the home for the video tutorials at Manning here, or watch a preview of the course here. To promote the launch, I have a special secret discount code ( vlgrummitt ) you can use to get 50% off, but you’ll need to move fast – it’s only valid until May 3.

You can use the video tutorials exclusively if you like, or even better – as an accompaniment to my book iOS Development with Swift, out now.

So if you’ve been thinking about learning iOS or Swift – now’s the time to dive in!

DbodW3zXcAAYTuR.jpg

 

Tagged with:
Posted in Swift

Learn iOS Development with Swift now!

Exciting news – the book I have been working on for almost two years, iOS Development with Swift, is now done, published, printed and available on Amazon or in a bookstore near you.

The book is aimed at experienced programmers looking to migrate into developing in iOS with Swift. It assumes no previous knowledge of Swift nor iOS but skips over all the stuff you’ll already know from your experience in other languages.

After getting you up to speed on what’s new and exciting in Swift, the book takes you through building up an app from zero to App Store, exploring many different challenges you may encounter when working on an app, such as:

  • How do you deal with different devices or orientations?
  • What do you do if the keyboard pops up and covers the text field the user is editing?
  • What are different ways of navigating between scenes?
  • How do scenes communicate with each other?
  • How can you integrate animation and adaptive layout?
  • How can you handle background tasks?
  • What are the different ways of storing data locally and in iCloud?
  • What options are available for debugging in Xcode?

I’m very much looking forward to seeing the apps that readers produce after exploring iOS development with the support of the book! Do let me know about your app creations via Twitter, and I’ll post them on the website for the book.

If you’re interested in taking a peek at iOS Development with Swift, you can check it out now as a live book using Manning’s online reader.

Posted in Swift

Migrating from AS3 to Swift

As iOS 11 no longer supports 32 bit apps, I’ve been revisiting an old app that was built in Flash/ActionScript3 (and packed in 32 bit) and decided it was an opportune moment to migrate it to native iOS Xcode/Swift. Migration was quite an interesting experience, and ultimately gave me a new appreciation for Xcode/Swift, especially auto-layout, size classes, enums and type-strictness.

In general, the app looks and acts virtually identically to its predecessor. Here is the main menu for you:

beforeAfter1.jpg

But in some cases, a change was necessary. As Flash did not have access to native controls, a custom solution was used using a Starling framework called Feathers. Of course from Xcode/Swift native controls were available. I used form builder Eureka to build this up. Here’s the difference:

beforeAfter3.jpg

Charts looked a little differently too. Charts in Flash used a long-dead yahoo framework called Astra. Charts now use Daniel Gindi’s huge Charts framework, which adds some pretty cool features such as pinch to zoom and drag. Here’s the difference:

beforeAfter4.jpg

One problem that I wasn’t able to resolve was detecting data from the old version of the app in new version of the app. I couldn’t find technical information on how Air’s SharedObject was implemented, so unfortunately data has to be reset from this version. Still, better than the app simply not working!

If you’re interested in checking out the new version of the app, you can find it here.

 

 

 

Tagged with:
Posted in AIR, Flash, Swift

Migrating to Codable from NSCoding

For those who came in late: Apple introduced the `Codable` protocol in Swift 4, which allows you to encode and decode your model types to data types such as JSON and property lists, and can be used instead of the `NSCoding` protocol to archive your data.

First of all, what’s the big deal with this Codable protocol? Is it really worth the effort to learn a new approach when we already have NSCoding, that’s worked fine for years for archiving data? And if you look at a type implementing both, they are pretty similar.

Imagine we have a Product type, that contains a title, price, and quantity:

struct Product {
 var title:String
 var price:Double
 var quantity:Int
}

Simple model type using NSCoding

Let’s look first at how we would implement this type using NSCoding:

class Product: NSObject, NSCoding {
  var title:String
  var price:Double
  var quantity:Int
  enum Key:String {
    case title = "title"
    case price = "price"
    case quantity = "quantity"
  }
  init(title:String,price:Double, quantity:Int) {
   self.title = title
   self.price = price
   self.quantity = quantity
  }
  func encode(with aCoder: NSCoder) {
   aCoder.encode(title, forKey: Key.title.rawValue)
   aCoder.encode(price, forKey: Key.price.rawValue)
   aCoder.encode(quantity, forKey: Key.quantity.rawValue)
  }
  convenience required init?(coder aDecoder: NSCoder) {
   let price = aDecoder.decodeDouble(forKey: Key.price.rawValue)
   let quantity = aDecoder.decodeInteger(forKey: Key.quantity.rawValu  e)
   guard let title = aDecoder.decodeObject(forKey: Key.title.rawValue) as? String else { return nil }
   self.init(title:title,price:price,quantity:quantity)
  }
}

A few points:

  • We implemented the type as a class instead of a struct, as the type needs to subclass NSObject.
  • We created a Keys enum (or could have been a struct) with values are used to archive and unarchive the type’s properties.
  • We adopted the NSCoding protocol, and implemented its two required methods:
    • init which initializes the type based on decoded information from an NSCoder object.
    • encode which encodes the type into an NSCoder object.

Simple model type using Codable

Ok, now let’s look at how we could implement this type using Codable:

struct Product: Codable {
  var title:String
  var price:Double
  var quantity:Int
  enum CodingKeys: String, CodingKey {
    case title
    case price
    case quantity
  }
  init(title:String,price:Double, quantity:Int) {
    self.title = title
    self.price = price
    self.quantity = quantity
  }
  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(title, forKey: .title)
    try container.encode(price, forKey: .price)
    try container.encode(quantity, forKey: .quantity)
  }
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    title = try container.decode(String.self, forKey: .title)
    price = try container.decode(Double.self, forKey: .price)
    quantity = try container.decode(Int.self, forKey: .quantity)
  }
}

Well, that looks familiar:

  • There is a CodingKeys enum, this time defined that describes the properties to encode.
  • The Product type adopts the Codable protocol, and implements its two required methods:
    • init which initializes the type based on decoded information from a Decoder object.
    • encode which encodes the type into an Encoder object.

Comparing Codable with NSCoding

Here’s a look at the similarities between the two approaches, in defining the model type:

Model type using Codable protocol vs using NSCoding protocol

Why use the Codable protocol?

So — if they’re so similar, why bother?

Well, there are a few good reasons:

  • You may have noticed that the Product type in the Codable example is a struct rather than a class — it doesn’t have to be, it’s just that as types that implement the Codable protocol don’t need to subclass (a reminder — NSCoding types must subclass NSObject, and therefore must be a class) they are free to be any sort of type — class, struct or even enum. The power!
  • Though I’m focusing on archiving to disk in this article, the Codable protocol isn’t just useful for archiving, it is also useful for encoding or decoding data to different data types. At the time of writing this includes JSON and property lists.
  • If it’s only encoding or decoding you’re after (for example, you might just be receiving and decoding data from a remote API), you can simply adopt the Encodable or Decodable protocols.
  • Anyone with experience with Codable is probably screaming about this advantage at the screen by now! So…the magic of the Codable protocol is that it has the power to automatically generate both of its required methods (encode and init) and the CodingKeys enum. If you’re after a straightforward encoding/decoding of Codable properties in your type, you can leave these out, and allow the compiler to auto-generate them, wow!

Model type using Codable protocol — manually specified vs generating automatically.

Why would you ever manually compose Codable functions?

Auto-generation is awesome, but there are still several circumstances where you will need to forego the convenience of auto-generation, and manually compose one or all of these. For example:

  • One or more properties of the type may not be Codable. In this case, you’ll need to convert it to and from a Codable type.
  • The structure of the type may differ from the structure you want to encode/decode.
  • You may want to encode and decode different properties than the properties of the type.
  • You may want to use different names for properties in the type.

Comparing archiving with Codable and NSCoding

We’ve seen how defining the model type compares, but how does the actual archiving of data compare?

Here is arching and unarchiving data the Product class with NSCoding:

func storeProducts() {
  let success = NSKeyedArchiver.archiveRootObject(products, toFile: productsFile.path)
  print(success ? "Successful save" : "Save Failed")
}
func retrieveProducts() -&amp;gt; [Product]? {
  return NSKeyedUnarchiver.unarchiveObject(withFile: productsFile.path) as? [Product]
}

And here is archiving and unarchiving our Product struct with Codable:

func storeProducts() {
  do {
    let data = try PropertyListEncoder().encode(products)
    let success = NSKeyedArchiver.archiveRootObject(data, toFile: productsFile.path)
    print(success ? "Successful save" : "Save Failed")
  } catch {
    print("Save Failed")
  }
}
func retrieveProducts() -&amp;gt; [Product]? {
  guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: productsFile.path) as? Data else { return nil }
  do {
    let products = try PropertyListDecoder().decode([Product].self, from: data)
    return products
  } catch {
    print("Retrieve Failed")
    return nil
  }
}

You can see it is a little more wordy to use the Codable protocol.

This is due to two factors:

  • Encoding and decoding can throw errors with the Codable protocol. This is a good thing — it means your app is less likely to crash unexpectedly while encoding and decoding with the Codable protocol.
  • You need to manually request that your data type is encoded using a custom encoder, before passing it into be archived. (The same can be said in reverse for decoding and unarchiving.)

Migrating to Codable

So, you can see that implementing the Codable protocol vs the NSCoding protocol definitely has its benefits. The question is — what should we do with legacy projects that use NSCoding?

Well, certainly, we could do nothing. Apple hasn’t declared that they’re deprecating NSCoding, so you should be right to continue using it.

But if you do wish to update your code to the more modern Codable protocol, how…?

If we just switch our NSCoding type to a Codable type, and we run the app on a device with preexisting NSCoding data, the app won’t just fail when it tries to unarchive it as Codable data, it will crash with an NSInvalidUnarchiveOperationException. A disaster for your loyal users!

One solution is to adopt BOTH the Codable and the NSCoding protocols. The first time a legacy user uses the app, they will retrieve the data using the NSCoding protocol. Any subsequent time they save data, they will save it using the Codable protocol, and henceforth will purely be accessing their data via the Codable protocol. At some point in the distant future, you could decide to no longer support data stored using NSCoding.

Adopting both the NSCoding and Codable protocols is pretty straight-forward. Your model type that already adopts NSCoding just needs to also adopt Codable, and it will automatically synthesize Codable methods. That means, just a change to the class header: (assuming your model type doesn’t have a more complicated structure that requires manually composing Codable methods)

class Product: NSObject, Codable, NSCoding {

Retrieving data should now no longer crash if the stored data is legacy, as your Codable type also implements NSCoding and subclasses NSObject.

You will just need to update the retrieveProducts method, to handle the data regardless of whether it is encoded using NSCoding or Codable:

func retrieveProducts() -&amp;gt; [Product]? {
  let unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: productsFile.path)
  //Work with Codable
  if let data = unarchivedData as? Data {
    do {
      let decoder = PropertyListDecoder()
      let products = try decoder.decode([Product].self, from: data)
      return products
    } catch {
      print("Retrieve Failed")
      return nil
    }
  }
  // Work with NSCoding
  else if let products = unarchivedData as? [Product] {
    return products
  } else {
    return nil
  }
}

As we will store the data in Codable format regardless of how we have retrieved it, the store function shouldn’t change from how it was when storing Codable data.

That’s it! Your app should now be migrated to use Codable, and deal with any legacy NSCoding data. The next time the user saves data, they will be saving it to the Codable format.

 

Tagged with: , , ,
Posted in Swift