Appendix - Swift Basics
Swift is a modern programming language designed for building apps on iOS, macOS, watchOS, and tvOS. Compared to Objective-C, Swift offers a cleaner syntax and a more intuitive development experience, making iOS app development faster and more enjoyable. In this appendix, I'll give you a quick introduction to Swift. This isn't a full language guide but rather an overview of the key concepts you need to get started. For a complete reference, you can visit Apple’s official Swift documentation at https://swift.org/documentation/.
Variables, Constants, and Type Inference
In Swift, you declare variables with the var keyword and constants using the let keyword. Here is an example:
var numberOfRows = 30
let maxNumberOfRows = 100
These are the two keywords you need to know for variable and constant declaration. You use the letkeyword for storing a value that is unchanged. Otherwise, use var keyword for storing values that can be changed.
Isn't it easier than Objective-C?
What's interesting is that Swift allows you to use nearly any character for both variable and constant names. You can even use an emoji character for the naming.
You may notice a huge difference in variable declaration between Objective-C and Swift. In Objective-C, developers have to specify explicitly the type information when declaring a variable. Be it an int or double or NSString, etc.
const int count = 10;
double price = 23.55;
NSString *myMessage = @"Objective-C is not dead yet!";
It's your responsibility to specify the type. In Swift, you no longer need to annotate variables with type information. It provides a huge feature known as Type inference. This feature enables the compiler to deduce the type automatically by examining the values you provide in the variable.
let count = 10
// count is inferred to be of type Int
var price = 23.55
// price is inferred to be of type Double
var myMessage = "Swift is the future!"
// myMessage is inferred to be of type String
It makes variable and constant declaration much simpler, as compared to Objective-C. Swift provides an option to explicitly specify the type information if you wish. The below example shows how to specify type information when declaring a variable in Swift:
var myMessage: String = "Swift is the future!"
No Semicolons
In Objective-C, you need to end each statement in your code with a semicolon. If you forget to do so, you will end up with a compilation error. As you can see from the above examples, Swift doesn't require you to write a semicolon (;) after each statement, though you can still do so if you like.
var myMessage = "No semicolon is needed"
Basic String Manipulation
In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants:
let dontModifyMe = "You cannot modify this string"
var modifyMe = "You can modify this string"
In Objective-C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make a choice in Swift. Whenever you assign a string to a variable (i.e. var), the string can be modified in your code.
Swift simplifies string manipulating and allows you to create a new string from a mix of constants, variables, literals, as well as, expressions. Concatenating strings is super easy. Simply add two strings together using the + operator:
let firstMessage = "Swift is awesome."
let secondMessage = "What do you think?"
var message = firstMessage + secondMessage
print(message)
Swift automatically combines both messages and you should see the following message in console. Note that print is a global function in Swift to print the message in console.
Swift is awesome. What do you think? You can do that in Objective-C by using the stringWithFormat:method. But isn't the Swift version more readable?
NSString *firstMessage = @"Swift is awesome. ";
NSString *secondMessage = @"What do you think?";
NSString *message = [NSString stringWithFormat:@"%@%@", firstMessage, secondMessage];
NSLog(@"%@", message);
String comparison is more straightforward. You can use the == operator to compare two strings like this:
var string1 = "Hello"
var string2 = "Hello"
if string1 == string2 {
print("Both are the same")
}
Arrays
The syntax of declaring an array in Swift is similar to that in Objective-C. Here is an example:
Objective-C:
NSArray *recipes = @[@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich"];
Swift:
var recipes = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich"]
While you can put any objects in NSArray or NSMutableArray in Objective-C, arrays in Swift can only store items of the same type. In the above example, you can only store strings in the string array. With type inference, Swift automatically detects the array type. But if you like, you can also specify the type in the following form:
var recipes : String[] = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich"]
Swift provides various methods for you to query and manipulate an array. Simply use the count method to find the number of items in the array:
var numberOfItems = recipes.count
// recipes.count will return 5
Swift makes operations on array much simpler. You can add an item by using the += operator:
recipes += ["Thai Shrimp Cake"]
This also applies when you need to add multiple items:
recipes += ["Creme Brelee", "White Chocolate Donut", "Ham and Cheese Panini"]
To access or change a particular item in an array, pass the index of the item by using subscript syntax just like that in Objective-C and other programming languages:
var recipeItem = recipes[0]
recipes[1] = "Cupcake"
One interesting feature of Swift is that you can use … to change a range of values. Here is an example:
recipes[1...3] = ["Cheese Cake", "Greek Salad", "Braised Beef Cheeks"]
This changes the item 2 to 4 of the recipes array to "Cheese Cake", "Greek Salad" and "Braised Beef Cheeks". (Remember the first item in an array starts with the index 0. This is why index 1 refers to item 2.)
If you print the array to console, here is the result:
- Egg Benedict
- Cheese Cake
- Greek Salad
- Braised Beef Cheeks
- Ham and Egg Sandwich
Dictionaries
Swift provides three primary collection types: arrays, dictionaries, and sets. Now let's talk about dictionaries. Each value in a dictionary is associated with a unique key. To declare a dictionary in Swift, you write the code like this:
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
The key and value in the key-value pairs are separated by a colon. The key-value pairs are surrounded by a pair of square brackets, each of which is separated by commas.
Like array and other variables, Swift automatically detects the type of the key and value. But, if you like, you can specify the type information by using the following syntax:
var companies: [String: String] = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
To iterate through a dictionary, use the for-in loop.
for (stockCode, name) in companies {
print("\(stockCode) = \(name)")
}
// You can also use the keys and values properties to
// retrieve the keys and values of the dictionary.
for stockCode in companies.keys {
print("Stock code = \(stockCode)")
}
for name in companies.values {
print("Company name = \(name)")
}
To access the value of a particular key, specify the key using the subscript syntax. If you want to add a new key-value pair to the dictionary, simply use the key as the subscript and assign it with a value like below:
companies["TWTR"] = "Twitter Inc"
Now the companies dictionary contains a total of 5 items. The "TWTR":"Twitter Inc" pair is automatically added to the companies dictionary.
Set
A set is very similar to an array. While an array is an ordered collection, a set is an unordered collection. Items in an array can be duplicated. A set stores no repeated values.
To declare a set, you can write like this:
var favoriteCuisines: Set = ["Greek", "Italian", "Thai", "Japanese"]
The syntax is very similar to creating an array, but you have to explicitly specify the type Set.
As mentioned, a set is an unordered collection of distinct items. If you declare a set of duplicated values, the set will not store the duplicates. Here is an example:

Operations on sets are quite similar to an array. You can use for-in loop to iterate over a set. But to add a new item to a set, you can't use the += operator. You have to call the insert method:
To access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.