In this tutorial you’ll learn the basics of programming in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as Atom, SublimeText or VSCode.
Let’s dive into code practice whilst learning about Swift Programming. Whenever you see codes, try it in your favourite IDE. Note that if you are using Xcode’s Playground, you may output anything you want in the console by using:
print("Hello World!")
Constants and Variables
You use constants and variables to associate a name (such as firstName) with a value of a particular type (such as the String “Zakhia”). The value of a constant cannot be changed once set while the value of a variable can be changed later.
Declare constants and variables with the keywords let and var respectively. It is recommended to follow the camelcase convention of writing the names of constants and variables, with the initial letter in lowercase. For example, let’s say you want to declare a constant with the name firstName and value Zakhia:
let firstName = "Zakhia"
You may output the value of constant firstName in the Playground’s console by using:
print(firstName)
Now let’s say you want to declare a variable with the name dayOfMonth and initial value Sunday:
var dayOfMonth = "Sunday"
You can declare multiple constants or variables on the same line:
var x = 4, y = 3, z = 0
Type Annotations
You can provide a type annotation when declaring a constant or a variable by being specific of the kind of value it stores. Here is a type annotation example of a declared variable of type String:
var programmingLanguage: String
Now we can set a value to the declared variable programmingLanguage:
programmingLanguage = "Swift"
You can declare multiple variables of the same type on the same line:
var milkPrice, teaPrice, sugarPrice: Double
Note that type annotations are rarely used in practice. Declaring a constant or a variable with a value, will provide Swift enough knowledge to infer the type of the constant or variable declared.
String Interpolation
You already know how to output values of a constant or a variable with print(). To include some text with a constant or a variable value as output, you can do so as follows:
print("I love programming with \(programmingLanguage).")
Comments
Comments are descriptive texts you write to clarify the purpose of some code. They are ignored by the Swift compiler. You may write single-line or multi-line comments.
Single-line comments:
// Writing a comment on a single line.
Multi-line comments:
/*
Writing a comment on
multiple lines.
*/
Integers
Integers are whole numbers such as 19 and -22. The keyword Int can be used to denote an integer constant or variable. Let’s declare a constant x with an integer value of 4:
let x = 4
Floats
Floats are fractional numbers such as 2.99, -23.15. Swift provides two signed types of floating-point number:
- Double represents a 64-bit floating-point number with a precision of at least 15 decimal digits.
- Float represents a 32-bit floating-point number with a precision of 6 decimal digits.
Booleans
Booleans can either be true or false, which is referred as logical and the keyword Bool can be used to denote a boolean constant or variable.
let isRaining = false
let isSunny = true
Conditional Statements
Conditional statements, also known as if statements, can be used when some conditions must be met before executing some code. An example can be:
if isSunny {
print("I will go out!")
} else {
print("I won't go out!")
}
Tuples
Tuples can be used to group multiple values into a single compound value. The values in a tuple can be of any type. Here is a tuple in action:
let profile = (19, "Zakhia")
You can decompose the content of a tuple into separate constants or variables:
let (id, name) = profile
Or you can get each element values in a tuple using index numbers:
print("id: \(profile.0)")
print("name: \(profile.1)")
Alternatively, you can name each element in a tuple when declared:
let profile1 = (id: 19, name: "Zakhia")
You can then get each element values in that tuple:
print("id: \(profile1.id)")
print("name: \(profile1.name)")
Optionals
Optionals are used when a value is absent. If there is a value, you can unwrap that optional else there is no value. An example of an optional can be, declaring a constant number of type String and trying to convert that String value to Int:
let numberInString = "19"
let convertToNumber = Int(numberInString) // returns an Int? (Optional Int)
You can set an optional variable to a valueless state nil:
var description: String? = "An optional variable of String type with some value" // description contains a value
description = nil // description contains no value
If an optional variable is declared without a default value, Swift automatically assigns nil to it.
var title: String?
// title is assigned to nil automatically
Note that in Swift nil is considered as an absence of a value of a certain type.
If Statements and Forced Unwrapping
You can compare an optional against nil, using an if statement, to find out if it contains a value.
if convertToNumber != nil {
print("convertToNumber has an integer value")
}
Now that you know that convertToNumber has an integer value, you can get its value by putting an exclamation mark (!) after convertToNumber, known as forced unwrapping:
if convertToNumber != nil {
print("convertToNumber has integer value \(convertToNumber!)")
}
Always make sure that an optional has a value before doing a forced unwrapping.
Optional Binding
You can find out if an optional has a value and if it does, you can assign a new constant or variable to that value. This process is known as optional binding.
if let convertToNumber = Int(numberInString) {
print("convertToNumber has integer value \(convertToNumber)")
} else {
print("\(numberInString) conversion to Int failed")
}
Implicitly Unwrapped Optionals
When you’re sure an optional will contain a value immediately after it is declared and can be assumed that it will be available later as well, you can implicitly unwrap it by placing an exclamation mark (!) after the type.
// optional string
let text: String? = "Learn Swift Programming with Zakh"
let text2: String! = text!
// implicitly unwrapped optional
let text3: String! = "Coding is easy and simple with Swift"
let text4: String = text3
Reference
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html