Swift
optional parameter
default value
Swift function
programming tutorial

Default optional parameter in Swift function

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Swift default values and optional types are often discussed together, but they represent different design decisions. A default value allows argument omission, while an optional type allows nil input. Knowing when to use each leads to clearer APIs and fewer call-site surprises.

Default Parameter Values

Default values are declared in the function signature.

swift
1func greet(name: String = "Guest") {
2    print("Hello, \(name)")
3}
4
5greet()
6greet(name: "Ava")

If caller omits name, Swift inserts the default at compile time.

Optional Parameters

Optional parameters allow explicit nil.

swift
1func greetOptional(name: String?) {
2    let displayName = name ?? "Guest"
3    print("Hello, \(displayName)")
4}
5
6greetOptional(name: nil)
7greetOptional(name: "Ava")

Caller must still pass an argument unless a default is also declared.

Optional with Default Nil

You can combine optional and default.

swift
1func greetFlexible(name: String? = nil) {
2    let trimmed = name?.trimmingCharacters(in: .whitespacesAndNewlines)
3    let display = (trimmed?.isEmpty == false) ? trimmed! : "Guest"
4    print("Hello, \(display)")
5}
6
7greetFlexible()
8greetFlexible(name: nil)
9greetFlexible(name: "Ava")

This supports both omission and explicit nil semantics.

API Design Guidance

Use non-optional defaults when function always needs concrete value.

swift
func fetchUsers(limit: Int = 20) {
    print("Limit \(limit)")
}

Use optional when nil has special meaning.

swift
1func search(query: String?, category: String = "all") {
2    if let query {
3        print("Search \(query) in \(category)")
4    } else {
5        print("Show featured in \(category)")
6    }
7}

This distinction communicates intent better than using optionals everywhere.

Interaction with Argument Labels

Default values do not change label rules.

swift
1func createUser(name: String, role: String = "viewer") {
2    print("\(name) role \(role)")
3}
4
5createUser(name: "Mina")
6createUser(name: "Mina", role: "admin")

Labels remain part of API readability contract.

Defaults Versus Overloads

Defaults can replace repetitive overloads.

Overload-heavy style:

swift
func log(_ message: String) { print(message) }
func log(_ message: String, level: String) { print("[\(level)] \(message)") }

Single defaulted function:

swift
func log(_ message: String, level: String = "INFO") {
    print("[\(level)] \(message)")
}

Use overloads only when behavior, not just parameters, differs.

Protocol and Extension Nuance

Defaults are chosen based on static call-site type. With protocols and extensions, this can surprise teams during refactors.

swift
1protocol Greeter {
2    func greet(name: String)
3}
4
5extension Greeter {
6    func greet(name: String = "Guest") {
7        print("Hello, \(name)")
8    }
9}

Understand static typing context when relying on extension defaults.

Initializers with Defaults

Default values are especially useful for model and config initializers.

swift
1struct APIClientConfig {
2    let timeout: TimeInterval
3    let retries: Int
4    let baseURL: URL
5
6    init(baseURL: URL, timeout: TimeInterval = 30, retries: Int = 2) {
7        self.baseURL = baseURL
8        self.timeout = timeout
9        self.retries = retries
10    }
11}
12
13let config = APIClientConfig(baseURL: URL(string: "https://api.example.com")!)

This keeps call sites compact while still allowing override when needed.

Documenting Defaults for Consumers

When publishing shared APIs, include default behavior in doc comments. Callers may never pass a value and still depend on the implicit behavior, so changing defaults is effectively a behavioral change and should be versioned carefully. This is especially important for SDKs consumed by multiple teams. Defaults affect compatibility.

Unit Testing Default Paths

Test all argument modes:

  • Omitted argument.
  • Explicit custom value.
  • Explicit nil, if optional.

This prevents hidden behavior drift when defaults evolve.

Common Pitfalls

  • Confusing optional type with optional argument omission. Fix by treating them as separate features.
  • Using optional when default non-optional is clearer. Fix by modeling API intent explicitly.
  • Writing many overloads for simple defaults. Fix by consolidating with default values.
  • Hiding critical behavior behind undocumented defaults. Fix by documenting default semantics.
  • Forgetting protocol extension default dispatch nuance. Fix by testing call sites through protocol-typed references.

Summary

  • Default values and optional types solve different API design problems.
  • Use default values for omission convenience.
  • Use optionals when nil carries meaning.
  • Prefer defaults over redundant overloads when behavior is identical.
  • Validate omitted and explicit argument paths with tests.

Course illustration
Course illustration

All Rights Reserved.