Swiftpack.co -  Package - struuuuggle/UDPropertyWrapper
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
struuuuggle/UDPropertyWrapper
Yet another type-safed wrapper of UserDefaults
.package(url: "https://github.com/struuuuggle/UDPropertyWrapper.git", from: "0.0.2")

UDPropertyWrapper

Swift Package Manager compatible Version License Platform

Yet another type-safed wrapper of UserDefaults

Example

import UDPropertyWrapper

struct UserDefaultsStore {
  @UserDefault("age", defaultValue: 0)
  var age: Int
  
  // If you don't assign any value to `defaultValue`, `nil` will be inserted automatically.
  @UserDefault("lastName")
  var lastName: String?
}

Since UDPropertyWrapper is type-safed, you cannot assign a value to defaultValue ignoring the type associted to the property.

// ⛔️ Cannot convert value of type 'String' to expected argument type 'Int'
@UserDefault("age", defaultValue: "")
var age: Int

// ⛔️ 'nil' is not compatible with expected argument type 'Int'
@UserDefault("age", defaultValue: nil)
var age: Int

// ⛔️ Referencing initializer 'init(_:)' on 'UserDefault' requires that 'String' conform to ExpressibleByNilLiteral'
@UserDefault("lastName")
var lastName: String

Introducing some small extensions on UserDefault enables you to bind enumeration cases.

enum UDKeys: String {
  case userId, countryCode
}

extension UserDefault where T: Codable {
  init(_ key: UDKeys, defaultValue: T) {
    self.init(key.rawValue, defaultValue: defaultValue)
  }
}

extension UserDefault where T: ExpressibleByNilLiteral {
  init(_ key: UDKeys) {
    self.init(key.rawValue, defaultValue: nil)
  }
}

// ✨ Great!
@UserDefault(.userId)
var userId: String

// ✨ Awesome!
@UserDefault(.countryCode)
var countryCode: Int?

Requirements

  • Swift 5.3+
  • Xcode12.0+

Installations

CocoaPods

pod 'UDPropertyWrapper'

Swift Package Manager

GitHub

link
Stars: 0
Last commit: 6 weeks ago

Release Notes

6 weeks ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco