UDPropertyWrapper 0.0.2

UDPropertyWrapper 0.0.2

Maintained by struuuuggle.



UDPropertyWrapper

Swift Package Manager compatible

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