Menu
Coddy logo textTech

What Are Optionals

Part of the Fundamentals section of Coddy's Swift journey — lesson 11 of 86.

Sometimes a variable might not have a value at all. In Swift, we represent the absence of a value using optionals. An optional says "there is a value, and it equals x" or "there isn't a value at all."

To declare an optional, add a question mark ? after the type:

var nickname: String? = "Alex"
var age: Int? = nil

In the example above, nickname holds the value "Alex", while age holds nil — Swift's way of saying "no value." Regular variables cannot be nil, but optionals can.

Think of an optional as a box that might contain something or might be empty. Before using what's inside, you need to check if there's actually something there. This is a key safety feature in Swift that helps prevent crashes from unexpected missing values.

var score: Int? = 100
print(score) // Optional(100)

score = nil
print(score) // nil

Notice that when you print an optional with a value, it shows Optional(100) rather than just 100. To access the actual value inside, you need to unwrap the optional — which we'll cover in the upcoming lessons.

challenge icon

Challenge

Easy

Write a function createOptional that takes a number and returns a string showing how that number would look when printed as an optional.

When you print an optional that contains a value, Swift displays it in the format Optional(value).

Function syntax reminder: In Swift, a function that returns a value uses the -> arrow to specify the return type, and the return keyword to send back the result. For example:

func myFunction(param: Int) -> String {<br>    return "result"<br>}

You can build the return string using string interpolation: "Optional(\(value))" — the \(value) part inserts the number directly into the string.

Parameters:

  • value (Int): The number to wrap in optional format

Returns: A string in the format Optional(value) where value is the provided number.

Example: If the input is 100, return "Optional(100)"

Cheat sheet

In Swift, optionals represent the absence or presence of a value. An optional can either contain a value or be nil.

To declare an optional, add a question mark ? after the type:

var nickname: String? = "Alex"
var age: Int? = nil

Regular variables cannot be nil, but optionals can. Use nil to represent "no value":

var score: Int? = 100
score = nil

When printing an optional with a value, Swift displays it as Optional(value):

var score: Int? = 100
print(score) // Optional(100)

score = nil
print(score) // nil

Try it yourself

func createOptional(value: Int) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals