0Pricing
Swift Academy · Lesson

Common wrappers patterns (validation, caching)

Build common validation and caching wrappers: guard input, provide defaults, memoize expensive work, and expose helper flags via projected values.

What we will build

This lesson shows two practical patterns:

  • Validation: accept-or-fix inputs with defaults and messages.
  • Caching: store results, expose $helpers like clear() and isCached.

Validation: NonEmpty

@NonEmpty guards empty input and supplies a default. The projectedValue reports if the last set was auto-fixed.

@propertyWrapper
struct NonEmpty {
    private var value: String = ""
    private(set) var lastFixed: Bool = false

    var wrappedValue: String {
        get { value }
        set {
            if newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                value = "N/A"          // default fallback
                lastFixed = true
            } else {
                value = newValue
                lastFixed = false
            }
        }
    }

    var projectedValue: Bool { lastFixed } // $name -> was fixed?

    init(wrappedValue: String) { self.wrappedValue = wrappedValue }
}

struct Profile {
    @NonEmpty var displayName: String = "  "
}
var p = Profile()
print(p.displayName)  // "N/A"
print(p.$displayName) // true (was fixed)

All lessons in this course

  1. Creating wrappers, projectedValue
  2. Reusability and constraints
  3. Common wrappers patterns (validation, caching)
← Back to Swift Academy