Giter Club home page Giter Club logo

typeddefaults's Introduction

TypedDefaults

Language CocoaPods License Issues

TypedDefaults is a utility library to type-safely use NSUserDefaults.

Motivation

The talk Keep Calm and Type Erase On by Gwendolyn Weston at try! Swift 2016 is great and it inspired me to apply the technique Type Erasure for actual cases in app development.

Installation

  • Install with CocoaPods

    use_frameworks!
    
    platform :ios, '8.0'
    
    pod 'TypedDefaults'

Requirements

  • iOS 8.0+
  • Swift 4.0
  • Xcode 9

Features

  • Custom types can be type-safely stored in NSUserDefaults
  • Dependency Injection support

Usage

Custom types

Custom types can be type-safely stored in NSUserDefaults.
Custom types only need to adopt DefaultsConvertible protocol as described later. No need to inherit NSObject.
Therefore, Swift native Class Struct and Enum are available for custom types.(Of course, subclasses of NSObject are available.)

DefaultsConvertible protocol

public protocol DefaultConvertible {

    static var key: String { get }

    init?(_ object: Any)

    func serialize() -> Any
}

Custom types are stored in NSUserDefaults as AnyObject.
serialize() is called when saving and init?(_ object:) is called when getting from NSUserDefaults.

It's assuemd each custom type and one configuration used in app is one-to-one relation.
Therefore, key is prepared as type property in order to assign key to one custom type.

Example of custom type

This is an example of the custom type with flag for saving photo to CameraRoll and Photo Size as camera configuration.

struct CameraConfig: DefaultConvertible {
    enum Size: Int {
        case Large, Medium, Small
    }

    var saveToCameraRoll: Bool
    var size: Size

    // MARK: DefaultConvertible

    static let key = "CameraConfig"

    init?(_ object: Any) {
        guard let dict = object as? [String: Any] else {
          return nil
        }

        self.saveToCameraRoll = dict["cameraRoll"] as? Bool ?? true
        if let rawSize = dict["size"] as? Int,
         let size = Size(rawValue: rawSize) {
            self.size = size
         } else {
            self.size = .Medium
        }
    }

    func serialize() -> Any {
        return ["cameraRoll": saveToCameraRoll, "size": size.rawValue]
    }
}

Saving custom type to NSUserDefaults

PersistentStore is the class to save custom types to NSUserDefaults.
Below is the sample of how to use it.

/// Specify a custom type when initializing PersistentStore
let userDefaults = PersistentStore<CameraConfig>()

// Make an instance of CameraConfig
var cs = CameraConfig([:])!

// Set
userDefaults.set(cs)
// Get
userDefaults.get()?.size // Medium

/// Change the size
cs.size = .Large

// Set
userDefaults.set(cs)
// Get
userDefaults.get()?.size // Large

Dependency Injection support

NSuserDefaults is not Unit Test friendly because it persistently stores data on file system.
TypedDefaults has the types InMemoryStore AnyStore for Dependency Injection in order to test types which behave differently depending on custom types stored in NSuserDefaults.

InMemoryStore adopts DefaultStoreType protocol as well as PersistentStore.
However, InMemoryStore retains custom types only on memory, which is different from PersistentStore.
As for AnyStore, it is the type to abstract PersistentStore and InMemoryStore.

Example

This is the example to use InMemoryStore and AnyStore instead of PersistentStore at Unit Test.

There is a class called CameraViewController which inherits UIViewController.
It has a property config to retain a custom type saved in NSuserDefaults. To support Dependency Injection, set AnyStore as the type of config.

class CameraViewController: UIViewController {
    lazy var config: AnyStore<CameraConfig> = {
        let ds = PersistentStore<CameraConfig>()
        return AnyStore(ds)
    }()

    ...
}

Because the type of config is not PersistentStore but AnyStore, it can be replaced with InMemoryStore at Unit Test as below.

class CameraViewControllerTests: XCTestCase {
    var viewController: CameraViewController!

    override func setUp() {
        viewController = CameraViewController()

        let defaultConfig = CameraConfig([:])!
        let ds = InMemoryStore<CameraConfig>()
        ds.set(defaultConfig) //
        viewController.config = AnyStore(ds)
    }
}

Release Notes

See https://github.com/tasanobu/TypedDefaults/releases

License

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

typeddefaults's People

Contributors

tasanobu avatar kitoko552 avatar readmecritic avatar

Stargazers

frankfanslc avatar  avatar Yasin ATEŞ avatar Kenta Enomoto avatar Koichiro Oishi avatar  avatar Hideki Matsuoka avatar Yee Yong avatar  avatar Viraj Patel avatar  avatar 贲知鹏 avatar Christopher Webb avatar Michael Pchelnikov avatar mitsuse avatar Felix  avatar SunShijia avatar HaviLee avatar Yusuke Kita avatar Deepu Mukundan avatar Eralp Karaduman avatar Lucas Farah avatar Jin Sasaki avatar Bernhard Loibl avatar Ricki Y. HAN avatar  avatar CYANware Software Solutions avatar Meow avatar ikemai avatar Keita Ito avatar Pierre-Yves Lebecq avatar Vic Hudson avatar Ricardo Pereira avatar Vincent Peng avatar luohaoyuan avatar Venj avatar sgxiang avatar Steven Zhang avatar Hank Bao avatar Lex Tang avatar Bruno Godbout avatar Xie Wu avatar Mathias Amnell avatar mfks17 avatar moubuns avatar Donghua Li avatar  avatar 时点软件冯成林 avatar Damian Esteban avatar motokiee avatar Carabineiro avatar Antonio Rodrigues avatar Alessio Nonni avatar Martin Høst Normark avatar Malcolm Jarvis avatar Joshue Santibanez avatar Anat Gilboa avatar Prashanth avatar James Campbell avatar Leo Tumwattana avatar Michael Heck avatar Pierre Abi-aad avatar samuele coppede avatar Toto Tvalavadze avatar Chiharu Nameki avatar yao2030 avatar Yuki Nagai avatar KooFrank avatar Yasuaki Goto avatar Yuji Hato avatar Chris Williams avatar Lasha Efremidze avatar Teddy Newell avatar Mateusz "Serafin" Gajewski avatar Prinomen avatar Dariusz Rybicki avatar Rob Cecil avatar Bassem Youssef avatar Nattawut Singhchai avatar  avatar James Pamplona avatar howie avatar Paul Uhn avatar Jernej Zorec avatar Felix Barros avatar Arsen Gasparyan avatar Max Desiatov avatar Michael Mellinger avatar Seyhun Akyürek avatar Blair McArthur avatar Victor Wang avatar Cory Sullivan avatar Basem avatar Niel Joubert avatar TOYAMA Yosaku avatar Yasuhiro Inami avatar Emre Kucukayvaz avatar Jesse Armand avatar Shohei Kawano avatar Thomas Krajacic avatar

Watchers

James Cloos avatar Carabineiro avatar  avatar

Forkers

bnakum carabina

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.