Connect with us

Code

Defaults – Swifty and modern UserDefaults

Store key-value pairs persistently across launches of your app.

It uses NSUserDefaults underneath but exposes a type-safe facade with lots of nice conveniences.

It’s used in production by apps like GifskiDatoLungoBattery Indicator, and HEIC Converter.

For a real-world example, see the Plash app.

Defaults Highlights

  • Strongly typed: You declare the type and default value upfront.
  • Codable support: You can store any Codable value, like an enum.
  • NSSecureCoding support: You can store any NSSecureCoding value.
  • SwiftUI: Property wrapper that updates the view when the UserDefaults value changes.
  • Publishers: Combine publishers built-in.
  • Observation: Observe changes to keys.
  • Debuggable: The data is stored as JSON-serialized values.
  • Customizable: You can serialize and deserialize your own type in your own way.

Defaults Benefits over @AppStorage

  • You define strongly-typed identifiers in a single place and can use them everywhere.
  • You also define the default values in a single place instead of having to remember what default value you used in other places.
  • You can use it outside of SwiftUI.
  • Comes with Combine publisher.
  • Supports many more types, even Codable.
  • Easy to add support for your own custom types.
  • Comes with a convenience SwiftUI Toggle component.

Compatibility

  • macOS 10.13+
  • iOS 12+
  • tvOS 12+
  • watchOS 5+
Defaults on GitHub: https://github.com/sindresorhus/Defaults
Platform: iOS
⭐️: 1.2K
Advertisement

Trending