How to use optionals in Swift

5 Answers

0 votes
import Foundation

// Optional integer variable
var n: Int? = 213

// Function to show how the optional behaves
func showNumber(_ value: Int?) {
    if let number = value {
        print("The number is \(number)")
    } else {
        print("No number found")
    }
}

// Use the function
showNumber(n)

// Set it to nil and test again
n = nil
showNumber(n)



/*
run:

The number is 213
No number found

*/

 

 
 

 

 



answered Jun 13, 2023 by avibootz
edited 5 hours ago by avibootz
0 votes
import Foundation

// Swift optionals let a variable hold either a value or nil, and you use unwrapping 
// (if let, guard let, ??, or !) to safely access the underlying value.

// This unwraps only if the value exists. 
// guard let — great for early exits inside functions

// guard let — great for early exits inside functions

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

// Example usage:
let userInput: String? = "Mr Sponge"
greet(userInput)

// Try with nil
let noName: String? = nil
greet(noName)



/*
run:

Hello, Mr Sponge
Missing name

*/

 



answered Jun 13, 2023 by avibootz
edited 5 hours ago by avibootz
0 votes
var username: String? = "Kael"

// if let - unwrap an optional safely.

if let name = username {
    print("Welcome, \(name)")
} else {
    print("No username found.")
}



/*
run:

Welcome, Kael

*/

 



answered 4 hours ago by avibootz
0 votes
import Foundation

var username: String? = "Kael"

// if let - unwrap an optional safely.

var age: Int? = nil

if let userAge = age {
    print("User is \(userAge) years old.")
} else {
    print("Age not provided.")
}



/*
run:

Age not provided.

*/

 



answered 4 hours ago by avibootz
0 votes
import Foundation

// if let - unwrap an optional safely.

// Multiple Optionals
var firstName: String? = "John"
var lastName: String? = "Doe"

if let first = firstName, let last = lastName {
    print("Full name: \(first) \(last)")
} else {
    print("Missing first or last name.")
}



/*
run:

Full name: John Doe

*/

 



answered 4 hours ago by avibootz

Related questions

...