skip to content

In Swift, how do you store validation functions such as isNotEmpty in a dictionary of rules, and what type does each entry have?

level: juniorimportance: must knowfreq 60%

answer

  1. functions are ordinary values
  2. parameter types, arrow, return type
  3. the name without parentheses
  4. closures fit the same slot
  5. a lookup gives an optional function

basics

~20 s

A Swift function is a value with a function type such as (String) -> Bool. Naming it without parentheses, isNotEmpty rather than isNotEmpty(), yields the function itself, so it can sit in a [String: (String) -> Bool] dictionary, be passed or be returned.

solid answer

~40 s

Every Swift function has a function type built from its parameter types and its return type: `func isNotEmpty(_ text: String) -> Bool` has the type `(String) -> Bool`. Writing the name without parentheses refers to the function instead of calling it, so `let rules: [String: (String) -> Bool] = ["required": isNotEmpty]` stores it. Anything of that type fits the same slot: another global function, a nested function, a closure expression, a bound method such as `validator.isLongEnough`, and in argument position even an operator, as in `names.sorted(by: <)`. A stored function is called with ordinary call syntax, `rule(input)`. A dictionary subscript returns an optional, so a lookup is called through optional chaining: `rules["email"]?(input)` yields a `Bool?`.

code

swift · 19 lines
swift
func isNotEmpty(_ text: String) -> Bool { !text.isEmpty }
func isEmailShaped(_ text: String) -> Bool { text.contains("@") && text.contains(".") }

let rules: [String: (String) -> Bool] = [
    "required": isNotEmpty,        // the function itself, not a call
    "email": isEmailShaped,
    "short": { $0.count <= 40 }    // a closure has the same type
]

func failedRules(for input: String, in rules: [String: (String) -> Bool]) -> [String] {
    var failed: [String] = []
    for (name, rule) in rules where !rule(input) {
        failed.append(name)
    }
    return failed.sorted(by: <)    // an operator passed as a function
}

print(failedRules(for: "kata", in: rules))  // ["email"]
print(rules["email"]?("[email protected]") as Any)    // Optional(true)

go deeper

for a junior

Recall the shape of a function type, (String) -> Bool, and the difference between naming a function and calling it. Show a dictionary of rules and how you call one entry.

for a middle

Explain that global functions, nested functions, closure expressions and bound methods all fit one function-typed slot, why a dictionary lookup needs optional chaining, and how operators pass as functions.

for a senior

Point out what function values cannot do: no protocol conformance, so no == and no identity-based unregistering. Explain how keying rules by name or wrapping them in a type sidesteps that in a real validator.

for a principal

Frame function values as the lightest extension point a codebase has, and weigh them against named types when rules must be compared, logged, persisted or discovered by other teams.

## Functions have types In Swift a function is a **first-class value**: it can be assigned to a constant or variable, stored in a collection or a property, passed as an argument and returned from another function. Every function has a **function type**, written as its parameter types in parentheses, an arrow, and its return type: | Declaration | Function type | |---|---| | `func isNotEmpty(_ text: String) -> Bool` | `(String) -> Bool` | | `func hasMinimumLength(_ text: String, of length: Int) -> Bool` | `(String, Int) -> Bool` | | `func logFailure(_ message: String)` | `(String) -> Void` (also spelled `(String) -> ()`) | | `func loadDefaults() -> [String]` | `() -> [String]` | The parentheses around the parameter list are required even for one parameter: `String -> Bool` is rejected with "single argument function types require parentheses". Argument labels are **not** part of the type, so the second row's `of` label disappears from `(String, Int) -> Bool`. ## Referring to a function without calling it The single most important piece of syntax is the difference between a **reference** and a **call**: - `isNotEmpty` is the function itself, a value of type `(String) -> Bool`. - `isNotEmpty("kata")` is a call; its value is a `Bool`. - `isNotEmpty()` is a call with a missing argument and does not compile. That is why a validator can build a table of named rules. The dictionary's value type is the function type, and each entry is a function reference, not a result: ```swift let rules: [String: (String) -> Bool] = [ "required": isNotEmpty, "email": isEmailShaped ] ``` If you write `isNotEmpty()` in that literal, the compiler reports that it cannot convert a `Bool` to the expected dictionary value type `(String) -> Bool`. The type annotation is what catches the slip; with a zero-parameter function and no annotation, the call would quietly run once while the table is built. ## Where a function value can go Because a function type is a type like any other, it appears wherever a type can: - **A constant or variable**: `let check: (String) -> Bool = isNotEmpty`. - **A collection element**: `[String: (String) -> Bool]`, `[(String) -> Bool]`. - **A parameter**: `func validate(_ input: String, with rule: (String) -> Bool) -> Bool`. - **A return value**: `func rule(named name: String) -> (String) -> Bool`. - **A stored property** of a struct or class, such as a retry policy held by a networking helper. When a function type contains more than one arrow, it groups from right to left: `(Int) -> (Int) -> Bool` means a function that takes an `Int` and returns another function. ## What fits a function-typed slot A `(String) -> Bool` slot does not care how the value was written. All of these are the same kind of value, because global functions, nested functions and closure expressions are all closures in Swift's own terms: 1. A **global function** named by its base name: `isNotEmpty`. 2. A **nested function** declared inside another function and returned from it. 3. A **closure expression**: `{ $0.count <= 40 }`. 4. A **bound method** of an instance: `validator.isLongEnough`. 5. An **operator** where the context supplies the type: `sorted(by: <)` passes the `String` implementation of `<` as a `(String, String) -> Bool`. Outside an argument list the operator needs parentheses and a type, as in `let ascending: (Int, Int) -> Bool = (<)`. ## Calling a stored function A stored function is called exactly like a declared one: `rule(input)`. Two details catch people: - A **dictionary lookup** returns `Optional<Value>`, here `((String) -> Bool)?`. Calling `rules["email"]("x")` fails with "value of optional type '((String) -> Bool)?' must be unwrapped"; `rules["email"]?("x")` calls the rule only when it exists and produces a `Bool?`. - The call carries **no argument labels**, because the value's type has none. Picking a specific overload or labelled function by name is covered in more depth with function references and full names. ## Limits of function values Function types are structural, not declared types, so they **cannot conform to protocols**. Two `(String) -> Bool` values cannot be compared with `==`, which means a registry cannot ask "is this rule already registered?" by comparing functions; key the rules by name, as the dictionary does. Whether a stored function may outlive the call that received it is the subject of `@escaping`, covered in the Swift material on closures.

  • What happens if you write isNotEmpty() instead of isNotEmpty when filling the rules dictionary?
    `isNotEmpty()` is a call, not a reference. Here it does not compile: the call is missing its `String` argument, and its result would be a `Bool`, which cannot convert to the dictionary's value type `(String) -> Bool`. With a zero-parameter function and no type annotation, the call would compile, run once while the table is built, and store only its result.
  • Why does rules["email"]?(input) need the question mark?
    A `Dictionary` subscript returns an optional, so the lookup has type `((String) -> Bool)?`. Optional chaining calls the function only if the key exists and makes the whole expression `Bool?`, so a missing rule yields `nil` instead of a crash. Force-unwrapping with `!` would trap when the key is absent.
  • Can you compare two function values with == to check whether a rule is already in the table?
    No. Function types cannot conform to protocols such as `Equatable`, and the compiler rejects `==` on two `(String) -> Bool` operands. Identify rules by a key, as the dictionary does, or wrap each one in a type that carries its own identifier.

A function name is like a contact saved in your phone: storing isNotEmpty saves the contact so anyone can call it later, while isNotEmpty() dials it immediately and stores only what the call returned.

  • Writing isNotEmpty() in the dictionary literal stores the function for later.
  • A function's type keeps its argument labels, as in (text: String) -> Bool.
  • Only closure expressions can be stored in variables; named functions cannot.
  • Operators such as < cannot be passed where a function is expected.
  • A dictionary lookup returns the function itself, so rules[key](input) compiles.