Skip to content

Simple, Strongly Typed UserDefaults for iOS, macOS and tvOS

License

Notifications You must be signed in to change notification settings

nmdias/DefaultsKit

Repository files navigation

DefaultsKit

cocoapods compatible carthage compatible language swift

Giản thể tiếng Trung

DefaultsKit leveragesSwift 4's powerfulCodablecapabilities to provide aSimpleandStrongly Typedwrapper on top ofUserDefaults.It uses less than 70 lines of code to acomplish this.

Installation >>instructions<<

Usage

Instantiate, or get asharedinstance ofDefaults

letdefaults=Defaults()// or Defaults.shared

Then:

// Define a key
letkey=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 thehas()method instead of the optionalget(for:key).For complex objects it will prevent any unnecessary deserialization.

Implicit Member Expression

You can find a convenience wrapper for your keys by extendingDefaultsKey.This allows you useImplicit Member Expression:

// Extend with a custom key
extensionDefaultsKey{
staticletsomeKey=Key<String>("someKey")
}

// Then use it like this
defaults.set("Some key",for:.someKey)
defaults.get(for:.someKey)// Output: Some key

Complex objects

To store a complex object just conform to theCodableprotocol:

structPerson:Codable{
letname:String
letage:Int
}

Then:

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

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

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

And finally:

// Read it back
letperson=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 theCodableprotocol:

enumPet:String,Codable{
casecat
casedog
}

structPerson:Codable{
letname:String
letpets:[Pet]
}

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

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

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

License

DefaultsKit is released under the MIT license. SeeLICENSEfor details.

Help Wanted

Review/TranslateREADME.zh-CN.mdto 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 seeissue #1

Thank you 🙏