Learn Swift by Building Applications
上QQ阅读APP看书,第一时间看更新

Optional types

We are familiar with basic types and their forms, but now it's time to introduce the optional type(s). This is a new concept, compared to what we have in Objective-C, which helps developers to avoid common mistakes when they are working with data. To explain the optional type(s), we should present the problem they are solving.

When we are developing a program, we can declare a variable, and we should set it an initial value. Later in the code, we can use it. But this is not applicable in general. There may be some cases when the default value is to have NO-VALUE, or simply nil. This means that when we want to work with a variable which has NO-VALUE, we should check that. But if we forget the check, then while our app is executed, we can reach this strange state with NO-VALUE, and the app usually crashes. Also, the code which checks whether a variable contains a value is reduced, and the programming style is concise.

To summarize: optionals enforce better programming style and improve the code checking when the compiler does its job.

Now let's meet the optional types in the following code snippet:

var fiveOrNothing: Int? = 5
//we will discuss the if-statement later in this chapter
if let five = fiveOrNothing {
print(five);
} else {
print("There is no value!");
}

fiveOrNothing = nil

//we will discuss the if-statement later in this chapter

if let five = fiveOrNothing {
print(five);
} else {
print("There is no value!");
}

Every type we know so far has an optional version, if we can call it that. Later in the book, you will understand the whole magic behind the optional types; namely, how they are created. Here are some of those: String?, Bool?, Double?, Float?, and so on.

Until now, we have learned how to store data, but we don't know what kind of actions we can do with it. This is why we should get familiar with basic operations with the data. The operations are denoted with operators such as +, -, *, and /. These operations work with particular data types, and we have to do the conversion ourselves.

Let's check this code:

let number = 5
let pisor = 3
let remainder = number % pisor //remainder is again integer
let quotient = number / pisor // quotient is again integer

let hey = "Hi"
let greetingSwift = hey + " Swift 4!" //operator + concatenates strings