LeadKit/TIFoundationUtils
Alexander Rutsman 915ec53b8c chore: bump version 1.8.0 2021-11-15 18:17:53 +03:00
..
Sources docs: correct typo 2021-09-16 23:33:24 +03:00
README.md refactor: correct links 2021-08-16 13:10:06 +03:00
TIFoundationUtils.podspec chore: bump version 1.8.0 2021-11-15 18:17:53 +03:00

README.md

TIFoundationUtils

Set of helpers for Foundation framework classes.

CodableKeyValueStorage

Storage that can get and set codable objects by the key.

Implementations: UserDefaults

Example

struct ProfileInfo: Codable {
    let userName: String
}

Keys:

extension StorageKey {
    static var profileKey: StorageKey<ProfileInfo> {
        .init(rawValue: "profileKey")
    }

    static var onboardingFinishedKey: StorageKey<Bool> {
        .init(rawValue: "onboardingFinishedKey")
    }
}

Subscript example

var defaults = UserDefaults.standard
defaults[.profileKey] = ProfileInfo(userName: "John Appleseed")
defaults[.profileKey] = "Agent Smith" // this will threat compile error:
// Cannot assign value of type 'String' to subscript of type 'ProfileInfo'

@propertyWrapper example

final class ViewModel {
    @UserDefaultsCodableBackingStore(key: .profileKey, codableKeyValueStorage: .standard)
    var profile: ProfileInfo?

    // This will threat compile error:
    // Cannot convert value of type 'BackingStore<UserDefaults, Bool?>' to specified type 'ProfileInfo?'
    @UserDefaultsCodableBackingStore(key: .onboardingFinishedKey, codableKeyValueStorage: .standard)
    var wrongKeyProfile: ProfileInfo?

    // For primitive types we can't use default json decoder/encoder
    @UserDefaultsCodableBackingStore(key: .onboardingFinishedKey,
                                     codableKeyValueStorage: .standard,
                                     decoder: UnarchiverKeyValueDecoder(),
                                     encoder: ArchiverKeyValueEncoder())
    var onboardingFinished = false
}