قالب وردپرس درنا توس
Home / IOS Development / mikeash.com: Friday Q & A 2017-10-06: Type-Safe User Standards

mikeash.com: Friday Q & A 2017-10-06: Type-Safe User Standards



Friday Q & A 2017-10-06: Type-Safe User Standards

It's fun to imagine traditional techniques with a swift twist. I have implemented a kind of safe team on top of the venerable NSUserDefaults and I will discuss my small library today. Credit / blame for this idea goes to local reader José Vazquez, although he accidentally inspired it while talking about something else.

  • User Standards
    NSUserDefaults or only UserDefaults in Swift is a typical dynamic written strict-oriented Objective-C API. It stores string keys and property list values. This is perfectly fine, but I would do better. I came up with this wish list:

    1. Keys must be declared, not written ad hoc at the place of use. You can do this with UserDefaults by declaring string constants, but it's easy to get lazy and not do it.
    2. It should not be repeated in the usual case. A key string should be automatically made to match its identifier in the code.
    3. No casting should be required. Keys should have a value pair attached to them and the conversion is handled internally.
    4. It should interact evenly with the values ​​read and written directly through UserDefaults .
    5. Selection Type Types To Be Supported Through Codable .
    6. Default values ​​should be specified as part of the key instead of being registered separately.
    7. The value should be made available as a property so the goal can be to mutate methods and operators.

    Code
    As usual, the code is available on GitHub if you want to play with it or see it all in one place:

    https://github.com/mikeash/TSUD

    Example Use [1

    9659013] Before we get into the implementation, let's consider what it looks like using this API. It will inform the implementation choices and clarify why things work as they do.

    To declare a key, type a struct in accordance with the protocol TSUD . Inside, implementing a single static property called defaultValue containing the value to be returned if UserDefaults does not contain a value:

          struct            la [19659020] DefaultValue    =    12.0 
        } 
    

    To read or write the value, use [Size: [Size: 19659021] : fontSize . value )
    fontSize . value = 14.0

  • Since value is only a property you can make disruptive and unnatural things like + = to it.

    If you want to discover the lack of a value and handle it specially than get a default value, declare defaultValue


    Source link