0
0
Swiftprogramming~5 mins

Nil represents absence of value in Swift

Choose your learning style9 modes available
Introduction

Nil means there is no value. It shows something is empty or missing.

When you want to say a variable has no value yet.
When a function might not return a value.
When you want to clear a value from a variable.
When you want to check if something exists or not.
When working with optional values that can be empty.
Syntax
Swift
var name: String? = nil

Use ? after the type to make it optional, meaning it can hold a value or nil.

Assign nil to show no value is present.

Examples
This means age can be an integer or no value at all.
Swift
var age: Int? = nil
Here message has a value "Hello" and is optional.
Swift
var message: String? = "Hello"
Now message has no value, it is nil.
Swift
message = nil
Sample Program

This program shows how to use nil to check if a value exists. First, petName is nil, so it prints no name. Then we give petName a value and print it safely.

Swift
var petName: String? = nil

if petName == nil {
    print("No pet name given.")
} else {
    print("Pet name is \(petName!).")
}

petName = "Buddy"

if let name = petName {
    print("Pet name is \(name).")
}
OutputSuccess
Important Notes

Always use optional binding (if let) to safely use values that might be nil.

Force unwrapping with ! can cause errors if the value is nil.

Summary

Nil means no value or absence of value.

Use optionals (with ?) to allow nil values.

Check for nil before using optional values to avoid errors.