Saltar al contenido

Nil & Optional

En esta página

nil represents the absence of a value. A type that may be nil is an optional; the nil-safety operators (?., ??) — covered in Operators — let you work with them without crashing:

nil alongside the booleans; optional handling lives in the Operators chapter.

04-bool-and-nil.zolo
Playground
// Feature: bool, nil, optional `T?`

// Syntax: `true` / `false` / `nil`; `T?` for optional types

// When to use: boolean logic; `nil` for "absence"; `T?` for values

// that may be missing in the type system.


// Booleans.

let active = true
let done: bool = false

// Short-circuit in && and ||

let a = active && 1 < 2  // true

let b = done || 1 == 1  // true

print(a, b)

// Logical negation.

print(!active)  // false


// `nil` is the "empty" value — the only value of its type.

let nothing = nil
print(nothing)  // nil


// Truthiness: only `nil` and `false` are falsy. 0, "", []

// COUNT as truthy (Lua semantics).

if 0 { print("0 is truthy") }
if "" { print("empty string is truthy") }
if [] { print("empty array is truthy") }

// Optional: `T?` accepts `T` OR `nil`.

let name: str? = nil
if name == nil {
  print("no name")
}

// Use `??` for fallback.

let display = name ?? "anonymous"
print(display)  // anonymous

Consulta también

Buscar en Zolo

9 resultados

en