Simple, Strongly Typed UserDefaults for iOS, macOS and tvOS
Swift Ruby Objective-C
Switch branches/tags
Latest commit 7b8c458 Sep 1, 2017 @nmdias committed on GitHub Fixed if DEBUG typo #4
Permalink
Failed to load latest commit information.
DefaultsKit.xcodeproj Refactored unit test mocks Aug 24, 2017
Sources Fixed if DEBUG typo #4 Sep 1, 2017
Tests Refactored unit test mocks Aug 24, 2017
.gitignore 0.0.1 Aug 19, 2017
.swift-version 0.0.1 Aug 19, 2017
DefaultsKit.png 0.0.1 Aug 19, 2017
DefaultsKit.podspec Bumped podspec to version 0.0.7 Aug 24, 2017
INSTALL.md 0.0.1 Aug 19, 2017
LICENSE 0.0.1 Aug 19, 2017
Package.swift 0.0.1 Aug 19, 2017
README.md Updated README Aug 28, 2017
README.zh-CN.md add space around numbers Aug 29, 2017

README.md

DefaultsKit

cocoapods compatible carthage compatible language swift

简体中文

DefaultsKit leverages Swift 4's powerful Codable capabilities to provide a Simple and Strongly Typed wrapper on top of UserDefaults. It uses less than 70 lines of code to acomplish this.

Installation >> instructions <<

Usage

Instantiate, or get a shared instance of Defaults

let defaults = Defaults() // or Defaults.shared

Then:

// Define a key
let key = Key<String>("someKey")

// Set a value
defaults.set("Codable FTW 😃", for: key)

// Read the value back
defaults.get(for: key) // Output: Codable FTW 😃

Check if a key has a value:

if defaults.has(key) { 
    // Do your thing
}

If you just need to know that a key/value pair exists, without actually using the value, use the has() method instead of the optional get(for:key). For complex objects it will prevent any unnecessary deserialization.

Complex objects

To store a complex object just conform to the Codable protocol:

struct Person: Codable {
    let name: String
    let age: Int
}

Then:

// Create a key
let key = Key<Person>("personKey")

// Get an instance of your Codable conforming enum, struct or class
let person = Person(name: "Bonnie Greenwell", age: 80)

// Set the value
defaults.set(person, for: key)

And finally:

// Read it back
let person = defaults.get(for: key)
person?.name // Bonnie Greenwell
person?.age  // 80

Nested Objects

You can also use nested objects as long as they conform to the Codable protocol:

enum Pet: String, Codable {
    case cat
    case dog
}

struct Person: Codable {
    let name: String
    let pets: [Pet]
}

// Get a Codable conforming instante
let person = Person(name: "Claire", pets: [.cat])

// Set the value
defaults.set(person, for: key)

// And read it back
let person = defaults.get(for: key)
person?.name        // Claire
person?.pets.first  // cat

License

DefaultsKit is released under the MIT license. See LICENSE for details.

Help Wanted

Review/Translate README.zh-CN.md to Chinese

Chinese is the #1 spoken language in the world and I'd love to have DefaultsKit be more inclusive, unfortunately I don't speak Chinese. If you know chinese, and would like to help out, please see issue #1

Thank you 🙏