10 things I like about Swift

And how I went from complete beginner to feeling confident in building iOS apps in Swift

These are a few of my favorite things… about Swift

After just over 2 months of immersing myself in the Swift language and tinkering with iOS development, I thought I’d put together my thoughts on why I’ve begun to fully enjoy working in Swift and provide some resources on how I ramped-up from complete beginner to feeling confident in building iOS apps in Swift.

I come from a full-stack development background, which really means I can’t call myself an expert in any particular field of computer science :). But I’ve worked professionally in Python, Scala and Javascript, among a few others, so my perspective likely bleeds from my past experiences working in those languages.

Note: I have been working in Swift 3, Xcode 8 and iOS 10.

1. Readability

Programs must be written for people to read, and only incidentally for machines to execute. — Harold Abelson

This is a principle I try to live by as a software engineer. So far, Swift has felt expressive and easy to use, while maintaining readability for future-me (or anyone else). It has the feel of what I would think a “modern” language should be, leaning towards simple and as-you-would-expect syntax, doing away with noisy symbols and clunky syntax as a natural evolution from Objective-C.

Here’s an example of how some simple string formatting compares between Objective-C, Swift and Python:

// Objective-C
NSString *name = @"Nate";
NSString *str = [NSString stringWithFormat:@"Hello %@, how are you today?", name];
// Swift
let name = "Nate"
let str = "Hello \(name), how are you today?"
// Python
name = "Nate"
str = "Hello %s, how are you today?" % name

There were several Swift-isms that I had to get used to, and still more I’m learning everyday, but Swift has overall been an approachable language to read and write code in.

For a great article on some intermediate Swift syntax, check this out.

2. Functional programming

Swift isn’t purely a functional programming language, but firmly embraces higher-order functions such as map, filter, reduce and flatMap.

As a brief overview of how functional programming can simplify your code, here’s an example:

// Add 5 to each number in an array, and return the even results
let numbers = [1, 2, 3, 4, 5]
// The traditional, imperative way
var newNumbers: [Int] = []
for number in numbers {
let newNum = number + 5
if newNum % 2 == 0 {
newNumbers.append(newNum)
}
}
// The functional, declarative way
var newNumbersFP = numbers.map { $0 + 5 }.filter { $0 % 2 == 0 }

You could argue that the imperative way is more readable, particularly when functional chaining and code complexity gets out of hand, but think of these higher-order functions as an additional tool in your tool belt for certain use-cases.

Higher-order functions can be extremely powerful, so for a deeper dive, see this article.

3. Type safety

Swift introduces the Optional type, which safely handles the absence of a value. It forces us to handle the nil case explicitly to ensure we’re not making any bad assumptions about what a variable holds.

For example, when a variable is an optional String, we know that either the variable is a String OR the variable doesn’t have a value. Swift offers a few ways for us to handle this in a safe way (called safe unwrapping):

  • guard:
guard let str = strOptional else {
return
}
// str is now safely unwrapped and is guaranteed to be of
// String type from here on
  • if let:
if let str = strOptional {
print("This is a string: \(str)")
}
  • optional chaining:
class Person {
var pet: Pet? // the ? means pet is a Pet optional
}
class Pet {
var numberOfPets: Int = 3
}
let me = Person()
let numberOfPets = me.pet?.numberOfPets
// numberOfPets is an optional Int and will be safely set to nil
// if pet is nil
// Or use "if let" to safely unwrap:
if let petCount = me.pet?.numberOfPets {
print("Pet count is \(petCount)")
}
  • nil and conditional coalescing:
let numberOfPets = me.pet?.numberOfPets ?? 0
let hasPets = numberOfPets > 0 ? true : false
// this can be short-handed to: let hasPets = numberOfPets > 0

There’s a lot to be appreciated with type safety in Swift, and many ways to go about structuring code to be safe and readable using these approaches. It can be frustrating at first because Swift urges for explicit handling of optionals (but doesn’t force safety on you!… see forced unwrapping), making it hard to write hack-y code. But just remember, Xcode is your friend and works with you when using optionals!

Xcode is your friend!

At the end of the day, Swift was built with safety in mind, intended to prevent many classes of bugs and runtime errors. It may mean that the language feels more strict, but their hope was that proper and explicit handling of types saves time in the long run.

4. Protocol-oriented programming

I’ll admit, this one took a bit of time to even begin to sink in. There is a lot out there on protocol-oriented programming (POP), structs and value type semantics, don’t repeat yourself (DRY principle) and then there’s the infamous Crusty talk; so this was an overwhelming topic early on for me, and still continues to be.

But things began to click as I dove in and started restructuring my code to use protocols and protocol extensions. By implementing and conforming my classes and structs to protocols (blueprints), and defining protocol extensions (default method implementations), I started seeing patterns of reusability and more modular code, and watched as my Massive View Controllers shrunk in size becoming more manageable. A great side-effect was that I was leaning towards composition as opposed to inheritance, so I wasn’t bloating my objects by super-classing and inheriting properties and methods I didn’t need.

I’m not doing POP justice with this bullet point. There seem to be endless use-cases for taking advantage of all that Swift has to offer with using protocols and value types, and I know I’ve only scratched the surface. Post a comment if you have any POP examples worth sharing!

In addition to the links above, here are a few more resources that I found helpful as I continue to wrap my head around this topic:

5. Property observers

This is one of my favorite out-of-box features of Swift. Understanding how it works is fairly simple with an example:

var score = 0 {
willSet {
print("Score is about to change to \(newValue)")
}
didSet {
print("Score just changed from \(oldValue) to \(score)")
}
}
score = 50
// Score is about to change to 50
// Score just changed from 0 to 50

One of my favorite ways of using property observers is with updating a table view:

var toDoListTasks: [Task] = [] {
didSet {
DispatchQueue.main.async {
self.tasksTableView.reloadData()
}
}
}
toDoListTasks.append(Task("clean kitchen"))
// table view is automatically reloaded!

Note from Apple docs:

The observers [willSet, didSet] are not called when the variable or property is first initialized. Instead, they are called only when the value is set outside of an initialization context.

6. Type inference

The Swift compiler infers type for constants or variables, allowing you to keep your code shorter and cleaner.

var number = 5              // Don't need to use var number: Int = 5
let pi = 3.14159 // pi is inferred to be of type Double
let stillPi = 3 + 0.14159 // Yup, still a Double
view.backgroundColor = .yellow   // Don't need to use UIColor.yellow

7. Custom function argument labels

Another small but nice feature of Swift: custom and omitted argument labels in functions for easier-to-read code.

func moveBox(_ box: Box, from start: Point, to end: Point) {
// move the box!
}
let aBox = Box()
moveBox(aBox, from: Point(0,0), to: Point(5,5))

Xcode then makes it super easy for you to fill out arguments when calling the method.

Again, Xcode is your friend!

8. Swift Playground

Since Swift’s initial release in 2014, playgrounds in Xcode have been around, allowing developers to quickly experiment with live code in an interactive environment, instead of having to continually go through a compile-run-test cycle.

Coming from a Python environment, I would have felt empty inside if this wasn’t possible with Swift, but I think playgrounds are to be appreciated for a compiled language! Swift playgrounds aren’t perfect and can get bogged down and slow to use in Xcode, but it’s still been super helpful as I’ve ramped-up and experimented with Swift code.

I haven’t yet used playgrounds for UI mockups, but I can only imagine how powerful and lightweight it must feel for those used to developing for iOS in Objective-C without the ability to quickly experiment.

9. Open-source

Want to know how Strings or Collections or anything else in the Swift standard library works? Or how about even lower-level implementation details of the Swift language? Well now you can! Swift has been open-sourced since Swift 2.2, and the Swift Evolution project continues to provide transparency with what’s coming in future releases of Swift.

Chris Lattner (founder of Swift) and team knew from day one that Swift would eventually be open-sourced, so kept full commit history all the way back to their very first commit. If you notice in those files, the copyright text says “Copyright © 2014–2015 Apple Inc.”, whereas the checkin was made in 2010! So it could be that 1) the team rewrote git history for some reason, 2) this was intentional to remind them that Apple wanted them to deliver in 2014–2015, or 3) Chris Lattner is a sorcerer.

10. Swift documentation

Apple’s Swift documentation reads like a book. They explain things in simple-to-understand English while laying out great examples, and I oftentimes find answers to my questions directly from their docs (as opposed to Stack Overflow), which I cannot say about other languages I’ve worked in.

I’ve learned about how closures and automatic reference counting work directly from the Swift docs, and even began my Swift journey on their Jump Right In page by building out a simple table view app. They’ve done a really great job with these docs and I’d highly recommend going directly to them before heading to Stack Overflow when working through your next problem.

11. Community

Ok I couldn’t leave this one out, so it’s going to be 11 things I like about Swift.

The Swift community has been more than welcoming as I’ve learned the ins-and-outs of iOS development, working in Xcode and ramped-up on Swift.

First, I love how there have been standards put forth from the wild that seem to have mass adoption, like Ray Wenderlich’s Swift style guide and the super customizable SwiftLint project from Realm for enforcing those standards, driven by the community. It’s given me comfort in knowing that there’s a well established way of doing things that much of the community agrees with, allowing me to focus on the important stuff.

Second, the active, online community of people who have willingly lended a helping hand as I worked through problems and had iOS/Swift related questions. Over my last couple months, I’ve leaned on the iOS developers Slack group, iOS developers on Twitter and countless websites and bloggers dedicated to teaching newbie iOS developers like myself.

Finally, those who built and contributed to the open-source project that is Swift. They’ve clearly built something that people love (4th most loved language!) and we shouldn’t take for granted all the work that has paved the way to what Swift is today.

Before you go…

You might be saying to yourself… this dude can’t possibly have nothing bad to say about Swift?! You’re right, there are certainly things that come to mind that have frustrated me about working in the language. To name just a few: lack of modules/namespacing (although there are tricks), JSON serialization using just Swift Core Libraries was a pain (I’m now using SwiftyJSON) and String manipulation and various String operations were brutal to work with (for good reason; but there seem to be a lot of improvements coming in Swift 4).

I opted to stick with the positives, as my overall experience with Swift has been beyond positive. I have so much more to learn (and be frustrated with), so figured that topic can wait.

Lastly, here’s a list of places I’d recommend for those just starting to learn Swift and iOS development that really helped me:

You can reach me on Twitter @nathanwchan, or leave a comment below. I’ll also be attending 360iDev in Denver this month (August 2017) to continue my Swift and iOS journey, so if you’re going to be there, don’t be a stranger!