SF Symbols in iOS 13

I was playing with the amazing SwiftUI with Apple’s tutorials (stay tuned, I hope to write something on SwiftUI soon) when I noticed something interesting:

Screen Shot 2019-06-06 at 8.55.02 pm.png

Where does this “star.fill” come from, I wondered… There’s no “star.fill” in the asset catalog?! It turns out the clue was in the initializer parameter “systemName”.

So from iOS 13, UIImage can now be initialized with systemName, which generates a “system symbol image”.  What are these “system symbol images”? Well, Apple has provided a program called “SF Symbols” that lets you browse all 1,500+ of them! You can download the program at their Apple Design Resources page.

Screen Shot 2019-06-07 at 9.16.15 am.png

Here are just some of the SF Symbols!

And it couldn’t be easier to use:

Screen Shot 2019-06-06 at 11.33.39 pm.png

There is a WWDC session on SF symbols well worth checking out here. You’ll also find Apple’s guidelines for using SF Symbols in the Human Interface Guidelines here. You’ll also find guidance there for building your own SF Symbol, using the SF Symbols program.

In the SF Symbols program you’ll notice you can play with the weight and scale of the image. You’ll find an example of these in the Human Interface Guidelines:


You can adjust the weight and scale of the image, along with its pointSize, using a config property:

Screen Shot 2019-06-06 at 11.44.22 pm.png

It should be noted that pointSize refers to a typographical point size – the same point size a font uses – rather than points on the screen.

Why have both pointSize and scale, you might ask. Well, the scale property allows you to adjust the scale of a symbol in relation to the text around it without having to adjust the pointSize. Perhaps you might be lining up an image with a label, adding an image to a button, or even inserting an SF symbol in a string! It should be mentioned that inserting an SF symbol into a string isn’t working yet for the current beta of Xcode 11, but it sounds very promising, adjusting the style of the symbol to the text surrounding it!

Having point size available is great, but we generally try to avoid specifying a point size with text — instead we prefer to use text styles, such as Body, Headline, etc where possible to take advantage of dynamic type. This is possible with SF symbols too — instead of specifying the point size, you can create the config property using a text style, just as you might with a label or text field:

Screen Shot 2019-06-07 at 1.18.28 pm.png

By the way, so far we’ve been looking at how to add SF symbols in code. We also saw at the start of this post that you can also include SF symbols in SwiftUI views.You might be interested to know you can also add them in the storyboard:

Screen Shot 2019-06-07 at 12.08.55 pm.png

Of course, as we saw at the start of this post, you can also include SF symbols in SwiftUI views.

Well, that’s the basics – there’s a lot more to look at – such as alignment, automatic configuration based on size class, making your app with SF symbols compatible with devices with < iOS 13, and building your own SF symbols. Again, I recommend you check out the WWDC session on SF symbols here.

In conclusion I think this is a really welcome addition to Xcode/iOS – apps will have a more consistent look across iOS, and I think SF symbols should make life much easier for us – less time for example, taken up sourcing icons and finding (or designing) a variety of sizes and weights. What do you think?

Tagged with: , , , ,
Posted in Swift

Swift 5 – it’s alive!

its-alive.jpgIt’s been a couple of weeks now since Swift 5 has arrived, with a bunch of features, such as:

  • ABI stability
  • source compatibility
  • isMultiple – a fancy technique for checking if a number is a multiple of another number.
  • Dictionary compactMapValues – finally we can properly compactMap a dictionary!
  • Result type – handle results from aynchronous code in a much cleaner way.
  • Raw strings – again Swift has had some enhancement to handling Strings.
  • And more!

If you want to a refresher on one or more of these features, I go into them in detail in a new Medium post, you can check it out here.

Tagged with:
Posted in Swift

Optionals in Swift explained – with a cat in a box!

If you’ve come to Swift from a language that doesn’t use optionals, you might find the concept a little strange and the syntax unfamiliar at first. Sometimes it helps to learn the unfamiliar with something familiar – in my lightning tour of optionals, I explain optionals with a cat in a box!

So – imagine you have a box:


Inside the box you know you have one of two things – either no cat…


…or a cat!


What you have just imagined, is a Cat optional!


As you can see, you declare an optional with the data type of its contents (Cat in this example), followed by a question mark:

var cat:Cat?

But now that we have a Cat optional, how do we get at its contents – or put another way – how do we unwrap the box?

Check my lightning tour of Optionals to find out:

Tagged with:
Posted in Swift

Get a continent from longitude-latitude

For a project I’m working on I needed to know if a point (latitude,longitude) was in a continent, and if so, which one!

To do this, first I set up a Continent enum to work with, making it a String (to easily print) and CaseIterable (to iterate through the cases later):

enum Continent:String,CaseIterable {

    case australia
    case northAmerica
    case southAmerica
    case africa
    case europe
    case asia
    case antarctica

I found this stackoverflow post, which though it wasn’t written in Swift, gave some very general polygons that vaguely encompassed the seven continents, exactly what I needed:


I first set up a utility method to convert a latitude and longitude array into a GMSMutablePath. (I’m going to solve this using the Google Maps SDK)

I then used the polygons from the StackOverflow post and converted the Latitude and Longitude arrays into paths in static variables in the Continent enum:

class Mapper {
static func getPath(lat:[CLLocationDegrees],long:[CLLocationDegrees])->GMSMutablePath {
let path = GMSMutablePath()
for i in 0..<lat.count {
path.add(CLLocationCoordinate2D(latitude: lat[i], longitude: long[i]))
return path
enum Continent:String,CaseIterable {
case australia
case northAmerica
case southAmerica
case africa
case europe
case asia
case antarctica
static var australiaPath:GMSMutablePath = Mapper.getPath(lat: [-11.88, -10.27, -10, -30, -52.5, -31.88],long: [110, 140, 145, 161.25, 142.5, 110])
static var africaPath:GMSMutablePath = Mapper.getPath(lat: [15, 28.25, 35.42, 38, 33, 31.74, 29.54, 27.78, 11.3, 12.5, -60, -60],long: [-30, -13, -10, 10, 27.5, 34.58, 34.92, 34.46, 44.3, 52, 75, -30])
static var europePath:GMSMutablePath = Mapper.getPath(lat: [90, 90, 42.5, 42.5, 40.79, 41, 40.55, 40.40, 40.05, 39.17, 35.46, 33, 38, 35.42, 28.25, 15, 57.5, 78.13],long: [-10, 77.5, 48.8, 30, 28.81, 29, 27.31, 26.75, 26.36, 25.19, 27.91, 27.5, 10, -10, -13, -30, -37.5, -10])
static var asiaPath:GMSMutablePath = Mapper.getPath(lat: [90, 42.5, 42.5, 40.79, 41, 40.55, 40.4, 40.05, 39.17, 35.46, 33, 31.74, 29.54, 27.78, 11.3, 12.5, -60, -60, -31.88, -11.88, -10.27, 33.13, 51, 60, 90],long: [77.5, 48.8, 30, 28.81, 29, 27.31, 26.75, 26.36, 25.19, 27.91, 27.5, 34.58, 34.92, 34.46, 44.3, 52, 75, 110, 110, 110, 140, 140, 166.6, 180, 180])
static var asia2Path:GMSMutablePath = Mapper.getPath(lat: [90, 90, 60, 60],long: [-180, -168.75, -168.75, -180])
static var northAmericaPath:GMSMutablePath = Mapper.getPath(lat: [90, 90, 78.13, 57.5, 15, 15, 1.25, 1.25, 51, 60, 60],long: [-168.75, -10, -10, -37.5, -30, -75, -82.5, -105, -180, -180, -168.75])
static var northAmerica2Path:GMSMutablePath = Mapper.getPath(lat: [51, 51, 60],long: [166.6, 180, 180])
static var southAmericaPath:GMSMutablePath = Mapper.getPath(lat: [1.25, 1.25, 15, 15, -60, -60],long: [-105, -82.5, -75, -30, -30, -105])
static var antarcticaPath:GMSMutablePath = Mapper.getPath(lat: [-60, -60, -90, -90],long: [-180, 180, 180, -180])

view raw


hosted with ❤ by GitHub

Great! Now seeing if a point is inside a polygon is as simple as comparing a CLLocationCoordinate2D property with a GMSMutablePath property, and you can do that with the GMSGeometryContainsLocation function.

I set up a contains function in the enum that checks if a continent contains the point:

func contains(point:CLLocationCoordinate2D)->Bool {
    switch self {
    case .australia:
        return GMSGeometryContainsLocation(point, Continent.australiaPath, true)
    case .northAmerica:
        return GMSGeometryContainsLocation(point, Continent.northAmericaPath, true) ||
            GMSGeometryContainsLocation(point, Continent.northAmerica2Path, true)
    case .southAmerica:
        return GMSGeometryContainsLocation(point, Continent.southAmericaPath, true)
    case .africa:
        return GMSGeometryContainsLocation(point, Continent.africaPath, true)
    case .europe:
        return GMSGeometryContainsLocation(point, Continent.europePath, true)
    case .asia:
        return GMSGeometryContainsLocation(point, Continent.asiaPath, true) || GMSGeometryContainsLocation(point, Continent.asia2Path, true)
    case .antarctica:
        return GMSGeometryContainsLocation(point, Continent.antarcticaPath, true)

North America and Asia both have two have polgyons that represent their areas.

So now, to determine which continent contains a point, all we have to do is iterate through the cases of the Continent enum, calling the contains method. I set up a getContinent method to do this:

static func getContinent(at point:CLLocationCoordinate2D)->Continent? {
    for continent in Continent.allCases {
        if continent.contains(point: point) {
            return continent
    return nil

To see how this could be used, imagine you’ve set up a map view in a view controller, let’s call it MapViewController, and we’ve set the view controller as the map view’s delegate. You could set up the mapView:didTapAt method to be called when the user taps on the map. We could use the coordinate property passed into the method to determine which continent the user has tapped, simply by passing the coordinate property into the Continent.getContinent method:

extension TestMapViewController:GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        if let continent = Continent.getContinent(at: coordinate) {
Tagged with: ,
Posted in Swift

Getting the keyboard height

Some time ago I answered a question in StackOverflow comparing the keyboard height on the iPhone X and the iPhone 8:

I got these heights by:
1. Adding an observer of the UIResponder.keyboardWillShowNotification notification:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

(In fact, if we want all keyboard frame changes, we should probably be observing the keyboardWillChangeFrameNotification notification, I discuss this in my book.)

2. Adding the selector function to be called:

@objc func keyboardWillShow(_ notification: NSNotification) {

3. Then, within this function, we need to dig down a crazy chain of downcasts and optional unwrapping from the userInfo dictionary to extract the height out of the notification object:

if let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

Done! We have the keyboard height.

The person I was answering on StackOverflow was trying to display a view directly above the keyboard, and was confused about why it wasn’t displaying in the correct place. (I believe there was some confusion because of the safe area inset on the iPhone X.)

To illustrate that displaying the view was possible, I set up a red rectangle directly above the keyboard. I was recently asked on Twitter how I did this:

Well, pretty straightforward, actually. Now we have the keyboardRect, all I had to do was set up a CGRect just above it, convert that to a CAShapeLayer, give it a strokeColor and lineWidth, and add it to the view’s layer.

      let newRect = CGRect(x: 0, y: view.frame.height - keyboardRect.height - 100, width: keyboardRect.width, height: 100)
      let rectLayer = CAShapeLayer()
      rectLayer.path = CGPath(rect: newRect, transform: nil)
      rectLayer.strokeColor = UIColor.red.cgColor
      rectLayer.lineWidth = 5
Tagged with:
Posted in Swift

Lightning tour of closures in Swift


Check out this video tutorial with a lightning tour of closures in Swift. It covers:

  • Functions as data types
  • Basic closure syntax
  • Trailing closures


If you’re interested in more of these sorts of videos, I’ll be posting frequently over on the iOS Development with Swift YouTube channel, you can subscribe here. I’ll be posting about closures next!

You could also join the video course and you’ll have access to all 8 hours of video tutorials, exercises and more!

Tagged with: ,
Posted in Swift

Overloading functions with default parameter values

Here’s a Swifty conundrum for you!

First a quick recap. Here’s a simple function with no parameters. Call it and “Hello World” will print to the console.

Screenshot 2019-01-09 13.27.42.png

Here’s another function with the same name. This time it has a parameter with a default value. We can call it in exactly the same way, and the default value will be printed to the console.

Screenshot 2019-01-09 13.27.25.png

Here’s the conundrum.

What if both functions exist, as overloaded functions?

screenshot 2019-01-09 13.18.55

What would we expect to see in the console?

We have two overloaded functions, one with a parameter with default values and another with no parameters. The call to the function could theoretically call either, but the question is, which does the compiler choose to call?

Need some thinking time?


So! It turns out that the console will display “Hello Mars”!

The rationale seems to be that the function with fewer parameters is called. I’m not able to find a discussion of the Swift team’s reasoning behind this, but it is consistent with the ‘overload resolution’ decision made by the C# compiler. The philosophy is described here in Microsoft docs:

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call.

(“Optional parameters” in C# parlance are the equivalent of parameters with default values in Swift.)

If you would like a quick recap of overloading functions and default parameter values, check my previous blog post “Lightning tour of functions in Swift“.

Tagged with: , ,
Posted in Swift

Lightning tour of functions in Swift


Check out this video tutorial with a lightning tour of functions in Swift. It covers:

  • Parameter default values
  • Optional function parameters
  • Overloading a function

livevideo-ios-development-with-swift-in-motion (2)

If you’re interested in more of these sorts of videos, I’ll be posting frequently over on the iOS Development with Swift YouTube channel, you can subscribe here. I’ll be posting about closures next!

You could also join the video course and you’ll have access to all 8 hours of video tutorials, exercises and more!

Tagged with: , , , ,
Posted in Swift

iOS Video Course is live!

After many months of work, my video course iOS Development with Swift in Motion has recently launched over at Manning Publications.

If you’re interested in taking on iOS Development, but aren’t sure if you’re ready to take the plunge, I’d say go for it! I’ve developed this course especially for people with some programming experience, so that we can skip past programming basics and get straight to the interesting stuff – what’s new, different and exciting in Swift. After a lightning tour of Xcode and setting up interfaces in Interface Builder, we get onto the main project of the course. We follow the evolution of this app from the germ of an idea right through to building all sorts of interesting features, such as connecting to a web service, displaying data in a table, taking photos, scanning bar codes, searching and sorting data and drawing custom graphics. We finish off by actually distributing the app to the App Store.

I’m excited to share this course with you. I hope you’ll find it useful and helps you launch your own app on the App Store! Good luck with it. You can find more info on the course here.

livevideo-ios-development-with-swift-in-motion (2).png


Tagged with: ,
Posted in Swift

flatMap vs compactMap

In Swift 4.1, the flatMap function was divided into two functions. One kept the same name:


This method flattens a sequence.

Let’s say we have a two-dimensional array:

let a = [[0,1,2],[3,4,5]]

We can use the flatMap higher order function to ‘flatten’ this into a one-dimensional array:

let b = a.flatMap{$0} //b = [0, 1, 2, 3, 4, 5]

You could flatten a dictionary too – you would just need to specify what you want to flatten the values. Let’s say we have a dictionary of animals, divided into classes:

let animals = [
  "Mammals":["cat", "dog", "alpaca"],
  "Reptiles":["lizard", "goanna", "snake"]

You could flatten this into a one-dimensional array of all animals, ignoring class:

let flatAnimals = animals.values.flatMap{$0}
flatAnimals //["lizard", "goanna", "snake", "cat", "dog", "alpaca"]


In Swift 4.1, the second function of flatMap is now called compactMap. The compactMap higher order function will remove any nil elements from a sequence. Imagine you have an array of Int optionals that contains both Ints and nil:

let numbers:[Int?] = [0, nil, 1, nil, nil, 2]

You can use the compactMap method to remove any nil values from this array:

let compactNumbers = numbers.compactMap{$0}
compactNumbers  //[0, 1, 2]

You can compact a dictionary too but you’ll need to use the filter method. Here’s a dictionary with String optional values:

let snakes:[String:String?] = ["A":"Anaconda", "B":nil, "C":"Cobra"]

You can use the filter method to

let compactSnakes = snakes.filter {$0.value != nil }
compactSnakes //["A": "Anaconda", "C": "Cobra"]

You might be wondering why the compactMap function doesn’t accomodate dictionary. This will be addressed in Swift 5 with the new compactMapValues function:

let compactSnakes = snakes.compactMapValues {$0}

Here‘s the Swift evolution proposal for compactMapValues.

Tagged with: , ,
Posted in Swift