For my 8th day of 100 Days of Code, I’ve decided to tackle Hello World in Swift. If you didn’t know, last time we covered Objective-C, so it makes sense that we learn a little more about it’s replacement, Swift.
Table of Contents
As usual, I took to Wikipedia to learn more about the language of interest today.
According to Wikipedia, Swift is like Objective-C in that it is also a general-purpose programming language. In addition, it has many of the same features, but it was designed to be safer. For example, Swift includes some syntactic sugar to help deal with the pyramid of doom. To be honest, this was the first time I’ve heard about the pyramid of doom, so I’ll share an example in pseudocode:
bedroomHeight = getHouse(5).getBedroom(3).getSize().getHeight()
In this example, each method call depends on the object before it. In other words, how do we know we have a fifth house? Or, that the house has a third bedroom? Without any error checking, we can get null pointer exceptions. To solve this problem, we basically have to create a pyramid of doom which is a set of nested if statements that verify that an object exists before making a method call.
Swift introduces a nice syntax for handling the pyramid of doom issue known as optional chaining. It basically allows you to keep the nice syntax from above, but stops methods from running on null objects. I would share an example, but I think the article linked above covers it well enough.
Naturally, I’m no expert in Swift or Objective-C, so the remainder of the background includes a few notes from one of our contributors, Marty:
According to Marty, Swift is Apple’s open source programming language. It was first released in 2014, making it relatively young. Even so, it utilizes Apple’s long-running Cocoa and Cocoa Touch frameworks. It is also designed to be highly interoperatable with Objective-C, the language Apple wrote their native software in for several decades.
Swift builds off of older, Objective-C based code, but when it comes to syntax, it is really a hybrid of many popular programming languages. Swift code often reads a bit like Scala, a language which also takes a hybrid approach to syntax and which is gaining popularity in Android development. Similarly, Swift is highly associated with iOS development.
While Swift and Objective-C are similar languages, Swift does have a few key features that differ from its predecessor.
One immediately obvious difference between Swift and Objective-C, is that Swift code tends to be less verbose and contains fewer non-alphanumeric characters. Swift syntax emphasizes clarity to the human reader.
While Swift uses C-style curly braces for blocks of code, semicolons are optional, and Objective-C’s pound signs, “at” symbols, and brackets are rarely seen, except in bridging code that communicates with Objective-C.
Another distinct feature of Swift is the extensive use of protocols. A protocol is an abstract type that lists what properties and methods an object must have, without specifying how these should be implemented. In languages such as Java and C#, this abstract type is called an interface. Apple has described Swift as a protocol-oriented language, since protocols are used in many places where other languages would use class hierarchies.
Finally, Swift is very concerned with preventing crashes and errors. One of the ways this is done is via Optionals. Optionals are objects that can either contain a value of a certain type, or nil, a special construct indicating absence.
Optionals help prevent runtime errors. In Swift, an uninitialized variable will cause a crash. Optionals allow us to double-check if we received data from a network, accepted user input, or if the UI updated. Swift offers several other syntax features designed with runtime safety in mind, as we will see below.
Hello World in Swift
If you’re familiar with Python, you’ll be delighted to know that Hello World in Swift is exactly the same:
Just like Python, we can call print directly without the need for a main function or any additional libraries.
Normally at this point, I would start to break down the code. However, there’s not much to explain. Instead, let’s implement Hello World in Swift with optionals, a feature that doesn’t exist in many languages:
var printString: String? printString = "Hello, World!" print(printString!)
Now, we’re talking! In the first line, we declare a variable called printString with the Optional String type. In other words, we’ve created a variable that can store either nothing or a String. Then, we store our typical Hello World string in the new variable. Finally, we print that variable.
But, wait just a minute! What’s that exclamation point doing? That is the Force Unwrap Operator. If printString is really a container holding either nothing or a String, then we need some way to open that container. The force unwrap operator does just that. Otherwise, we would print:
And, that’s clearly not what we want. Now, keep in mind that forcefully unwrapping an optional is typically a bad decision. It’s just a fun language feature that I wanted to share.
At any rate, how cool is that? Optionals may just be one of my favorite language features since starting this journey. I can’t wait to see what else I’ll learn along the way.
How to Run the Solution
Just like normal, we can try using this online Swift compiler. Just copy the solution from above into the editor and hit run. The “Hello, World!” string should pop up in the console.
Alternatively, we can leverage Xcode if we’re Mac users—or have a macOS virtual machine lying around.
Sample Programs in Every Language
Now that we have Swift out of the way, I want to take a look at another company built language known as Go, also known as golang. With C# being a product of Microsoft and Swift being a product of Apple, I figured why not tackle a language developed by Google. That sounds fun, right?
Earlier this year, I had an idea to automate the Sample Programs website. Turns out, it wasn't that hard to do. Now, the website is automatically built on every pull request. Let's talk about...
This week, I made a quick article about a few of the things I hear a lot about what you need to know to be a developer. Not everything is true.