Swift Tutorial menu

Swift Conditions and Optionals

Conditions choose which code runs. Optionals let a value be missing safely.

if, else if and else

Swift does not need brackets around the condition, but the curly braces are required.

Example

swift
let temperature = 34

if temperature > 40 {
    print("Too hot, stay inside")
} else if temperature > 30 {
    print("Hot, drink lots of water")
} else {
    print("Nice weather")
}
Output
Hot, drink lots of water

switch

switch compares a value against many cases. In Swift:

  • A switch must cover every possible value, so you often need default
  • There is no automatic fall-through and no break needed
  • A case can match several values or a range

Example

swift
let marks = 78

switch marks {
case 90...100:
    print("Grade A+")
case 80..<90:
    print("Grade A")
case 70..<80:
    print("Grade B")
case 0..<70:
    print("Keep working")
default:
    print("Invalid marks")
}

let day = "Sunday"
switch day {
case "Saturday", "Sunday":
    print("Weekend")
default:
    print("Weekday")
}
Output
Grade B
Weekend
RangeMeaning
90...100closed range: 90 to 100, including 100
80..<90half-open range: 80 to 89

What is an Optional?

Sometimes a value may not exist. A user may not have a middle name. Converting "abc" to a number fails. Swift uses an optional for this. An optional either holds a value or holds nil.

Add ? after a type to make it optional:

Example

swift
var nickname: String? = nil
print(nickname ?? "No nickname")

nickname = "Aishu"
print(nickname ?? "No nickname")
Output
No nickname
Aishu

?? is the nil-coalescing operator. It uses the value if there is one, and the default otherwise.

Unwrapping with if let

To use the value inside an optional, you must unwrap it. if let does this safely: the code runs only when the value is not nil.

Example

swift
let input = "350"

if let price = Int(input) {
    print("Price with tax: \(price + 50)")
} else {
    print("That is not a number")
}

let phone: String? = nil
if let phone {
    print("Calling \(phone)")
} else {
    print("No phone number saved")
}
Output
Price with tax: 400
No phone number saved

if let phone is a short form of if let phone = phone, available since Swift 5.7.

guard let

guard checks a condition and leaves early if it fails. It keeps the main code less indented. It is common inside functions:

Example

swift
func greet(_ name: String?) {
    guard let name else {
        print("Hello, guest")
        return
    }
    print("Hello, \(name)")
}

greet("Hamza")
greet(nil)
Output
Hello, Hamza
Hello, guest

Avoid force-unwrapping with ! (like nickname!). If the value is nil, your app crashes. Use if let, guard let or ?? instead.

Exercise

Exercise

What does print(Int("12a") ?? -1) print?

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp