Hello World in Swift

Hello World in Swift Featured Image

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

Swift Background

As usual, I took to WikipediaOpens in a new tab. to learn more about the language of interest today.

Personal Research

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 chainingOpens in a new tab.. 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.

Phone-A-Friend

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 TouchOpens in a new tab. frameworks. It is also designed to be highly interoperatableOpens in a new tab. with Objective-COpens in a new tab., the language Apple wrote their native software in for several decades.

Swift builds off of older, Objective-C based codeOpens in a new tab., but when it comes to syntax, it is really a hybrid of many popular programming languages. Swift code often reads a bit like ScalaOpens in a new tab., a language which also takes a hybrid approach to syntax and which is gaining popularity in AndroidOpens in a new tab. development. Similarly, Swift is highly associated with iOSOpens in a new tab. development.

Features

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 clarityOpens in a new tab. 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 codeOpens in a new tab. that communicates with Objective-C.

Another distinct feature of Swift is the extensive use of protocolsOpens in a new tab.. A protocol is an abstract typeOpens in a new tab. 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 interfaceOpens in a new tab.. Apple has described Swift as a protocol-oriented languageOpens in a new tab., since protocols are used in many places where other languages would use class hierarchiesOpens in a new tab..

Finally, Swift is very concerned with preventing crashes and errors. One of the ways this is done is via OptionalsOpens in a new tab.. Optionals are objects that can either contain a value of a certain type, or nilOpens in a new tab., 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:

print("Hello, World!")

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:

Optional("Hello, World!")

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 compilerOpens in a new tab.. 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 XcodeOpens in a new tab. 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?

I don’t have many plans after that, but I’m interested in exploring Rust, PHP, and JavaScript soon. As far as the more esoteric languages go, I’d like to leave those until the end of this journey.

Sample Programs in Every Language (44 Articles)—Series Navigation

For 100 Days of Code, I’ve decided to implement a few sample programs in as many languages as possible. Each implementation details a brief history of the language and a description of the code.

The plan for the series is to explore the major general-purpose language like Java, Python, C, C++, and C#. From there, we’ll take a look at some sample programs in web development languages like Ruby, PHP, and JavaScript. As we continue, we’ll cover proprietary languages like Swift and Objective-C. Eventually, we’ll start to tackle less popular languages like Rust, x86, and Verilog. Finally, we’ll play around with some of the esoteric languages like Brainf*ck and LOLCODE.

Who knows? Maybe the Sample Programs in Every Language series will become so popular it’ll never end. To help this series grow, consider sharing it on social media with your friends. Or, if you have a language you want to see, drop your suggestion in the comments.

Jeremy Grifski

Jeremy grew up in a small town where he enjoyed playing soccer and video games, practicing taekwondo, and trading Pokémon cards. Once out of the nest, he pursued a Bachelors in Computer Engineering with a minor in Game Design. After college, he spent about two years writing software for a major engineering company. Then, he earned a master's in Computer Science and Engineering. Today, he pursues a PhD in Engineering Education in order to ultimately land a teaching gig. In his spare time, Jeremy enjoys spending time with his wife and kid, playing Overwatch 2, Lethal Company, and Baldur's Gate 3, reading manga, watching Penguins hockey, and traveling the world.

Recent Posts