mirror of
https://github.com/ivanvorobei/SwiftUI.git
synced 2026-03-23 18:01:16 +01:00
Add examples project
This commit is contained in:
28
Examples/Example To-Do App/SwiftUITodo/UserDefaultsValue.swift
Executable file
28
Examples/Example To-Do App/SwiftUITodo/UserDefaultsValue.swift
Executable file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// UserDefaultsValue.swift
|
||||
// SwiftUITodo
|
||||
//
|
||||
// Created by kemchenj on 2019/6/5.
|
||||
// Copyright © 2019 Suyeol Jeon. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
@propertyDelegate
|
||||
struct UserDefaultValue<Value: Codable> {
|
||||
|
||||
let key: String
|
||||
let defaultValue: Value
|
||||
|
||||
var value: Value {
|
||||
get {
|
||||
let data = UserDefaults.standard.data(forKey: key)
|
||||
let value = data.flatMap { try? JSONDecoder().decode(Value.self, from: $0) }
|
||||
return value ?? defaultValue
|
||||
}
|
||||
set {
|
||||
let data = try? JSONEncoder().encode(newValue)
|
||||
UserDefaults.standard.set(data, forKey: key)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user