Five Common Questions About Swift

Five Common Questions About Swift

Even though Swift may be reminiscent of several other programming languages, such as Ruby, Java, and JavaScript, it is dangerous to compare it with other languages. In this article, I answer five common questions about the Swift programming language.

1. What Is an Optional?

Optionals are an important concept in the Swift programming language. First, it is important to understand that the meaning of nil differs in Swift and Objective-C. In Objective-C, sending a message to nil doesn't do anything. This has it pros and cons, but that isn't the topic of this article.

In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language. The example below shows how an optional can be defined in Swift. If you browse Swift's source on GitHub, then you'll come across this concept.

enum Optional<T> {
  case None
  case Some(T)
}

To safely access the value of an optional, you first ask whether the optional contains a value. In Swift parlance, you safely unwrap the optional to access its value.

let message: String? = "Hello World"

if message != nil {
    print(message!)
}

if let unwrappedMessage = message {
    print(unwrappedMessage)
}

In the first example, we check whether message is equal to nil. If it isn't, we print the value stored in message. In the second example, we use optional binding to accomplish the same thing. We bind the value stored in message to the unwrappedMessage constant. The if clause is only executed if the value of message could be bound to unwrappedMessage. This is the preferred way to safely unwrap the value of an optional.

2. What Is the Meaning of ! In Swift?

In the answer to the first question, we already encountered the ! operator. In Swift, an exclamation mark has several meanings. The exclamation mark is commonly used to explicitly force an operation. For example, to force unwrap (as opposed to safely unwrap) an optional, you'd use the exclamation mark.

let message: String? = "Hello World"

print(message!)

Keep in mind that a fatal error is thrown if message doesn't contain a value. In other words, if you force unwrap an optional that doesn't have a value, your application crashes.

The exclamation mark is also used in error handling. If a function is throwing, you can ignore any errors that are thrown by appending an exclamation mark to the try keyword.

let data = try! NSData(contentsOfFile: path, options: [])

By using try! instead of try (or try?) error propagation is disabled. If the throwing method call does result in an error, a runtime error is thrown and your application crashes.

Think of the exclamation mark as a warning sign. It indicates that you are bypassing Swift's safety mechanisms. Think twice before using an exclamation mark in Swift, unless you are doing a comparison.

let a = 1
let b = 2

if a != b {
    print("\(a) is not equal to \(b)")
}

3. What Is the Difference Between var and let?

In Swift, a variable can be constant or variable. If the value stored in a variable doesn't change, it should be a constant variable. If the value of a variable changes, it should be a variable variable. Because constant variable and variable variable sound a bit odd, we generally refer to constants and variables instead.

Unlike C and Objective-C, constants are common in Swift and the syntax is clear and straightforward. The let keyword declares a constant variable. The var keyword declares a variable variable. It's that simple.

The compiler tells you when to use a constant instead of a variable if it sees the value of a variable doesn't change during its lifetime.

What Is the Difference Between var and let

4. What Separates Structures and Classes?

Even though structures and classes look very similar at first glance, there are a few key differences.

Structures don't support inheritance. Part of the power of classes is that classes can inherit state and behavior from other classes. Even though structures don't support inheritance, structures can extend their functionality by conforming to protocols.

Another important difference between classes and structures relates to the behavior of instances of classes and structures. Structures are value types and classes are reference types. What does that mean?

Every instance of a structure keeps a copy of its data. Instances of a class share a copy of the data. Instances of classes are passed by reference. This is a key difference that trips up many developers. The following example illustrates this difference.

struct Car {

    var topSpeed = 100

}

var car1 = Car(topSpeed: 120)
var car2 = car1

car1.topSpeed = 200

print(car1.topSpeed) // 200
print(car2.topSpeed) // 120

class Bike {

    var topSpeed = 120

}

var bike1 = Bike()
var bike2 = bike1

bike1.topSpeed = 200

print(bike1.topSpeed) // 200
print(bike2.topSpeed) // 200

There are a few more differences, but these are the most important ones that separate structures and classes.

5. What Are Stored and Computed Properties?

This question is best answered by looking at an example. In the following example, the Car class declare two stored properties, sizeFuelTank and fuelEfficiency, and one computed property, mileage.

class Car {

    var sizeFuelTank: Float = 100
    var fuelEfficiency: Float = 5

    var mileage: Float {
        return (sizeFuelTank / fuelEfficiency) * 100
    }
}

var car = Car()

car.sizeFuelTank = 50
car.fuelEfficiency = 5.5

print(car.mileage)

The stored properties of the Car class store a value. The computed property, however, doesn't store a value. It calculates or computes a value based on the state (the values stored in sizeFuelTank and fuelEfficiency) of the Car instance.

Another important difference is that stored properties are only provided by classes and structures. Enumerations can only declare computed properties.

What's Next?

Swift is a pretty unique programming language and the more I use it, the more I come to fall in love with the language. It takes time to become familiar with Swift's concepts and syntax, especially if you are coming from C or Objective-C. Questions? Leave them in the comments below or reach out to me on Twitter.