๐ก ์ ์ ๋ํดํธ์ ํน์ ํค(String ๊ฐ)์ ์์ ํ๊ณ ๊ฐ๋จํ๊ฒ ์ ๊ทผํ๋ ๊ณ์ฐ ํ๋กํผํฐ๋ฅผ ๋ง๋ค์๋ค.
- ํ์ง๋ง ์ด๋ `UserDefault.standard.๊ณ์ฐํ๋กํผํฐ = ๋ฐ๋ ๊ฐ` ํ์์ผ๋ก ์ฌ์ ํ ์ฝ๋๊ฐ ๊ธธ์๋ค.
- ์ด๋ฅผ ๋ ํธ๋ฆฌํ๊ณ ๊ฐ๋จํ๊ฒ ์ฌ์ฉํ๊ธฐ ์ํ Property Wrapper๋ฅผ ๋ง๋ค์๋ค.
ํ๋กํผํฐ ์ฌ์ฉ ๊ตฌ์กฐ
SwiftUI Environment์ ๋น์ทํ๊ฒ UserDefaults์ ์ ๊ทผํ ์ ์๊ฒ ๋ง๋๋ ๊ฒ์ด ๋ชฉ์
Environment ํ๋กํผํฐ ์ฌ์ฉ๋ฒ
@Environment(\.layoutDirection) var layoutDirection
Environment | Apple Developer Documentation
Environment | Apple Developer Documentation
A property wrapper that reads a value from a view’s environment.
developer.apple.com
๋ชฉํ ์ฌ์ฉ๋ฒ
@DefaultsState(\.๊ณ์ฐ_ํ๋กํผํฐ) var ๋ณ์
๋ฏธ๋ฆฌ ๋ง๋ค์ด ๋์ ๊ณ์ฐ ํ๋กํผํฐ:
extension UserDefaults{
var ๊ณ์ฐ_ํ๋กํผํฐ:ํ์
{
get{ self.ํ์
์ ๋ง๋ ๋ณํ(forKey: "ํค ๋ฌธ์์ด") }
set{
self.set(newValue,forKey: "ํค ๋ฌธ์์ด")
}
}
}
ํ๋กํผํฐ ๋ํผ ์ ์
์ ์ฒด ์์ ์ฝ๋
import Foundation
extension UserDefaults{
var hello:Int{
get{ self.integer(forKey: "hello") }
set{self.set(newValue,forKey: "hello")}
}
}
UserDefaults.standard.hello = 10
@propertyWrapper
struct DefaultsState<Value>{
private var path: ReferenceWritableKeyPath<UserDefaults,Value>
var wrappedValue: Value{
get{
UserDefaults.standard[keyPath: path]
}
set{
UserDefaults.standard[keyPath: path] = newValue
}
}
init(_ location:ReferenceWritableKeyPath<UserDefaults,Value>){
self.path = location
}
}
struct Hello{
@DefaultsState(\.hello) var wow
}
var h = Hello()
print(h.wow)
h.wow = 20
print(h.wow)
- ํ๋กํผํฐ ๋ํผ ๊ตฌ์กฐ์ฒด์
Value๋ผ๋ ์์ ํ์ ์ KeyPath์ ์ต์ข ๋ชฉ์ ํ์ ๊ณผ ๋ง์ถ์ด ๊ตฌ์กฐ์ฒด ์ ์ฒด(ํนํ, wrappedValue)์ ํ์ ์ถ๋ก ์ด ๊ฐ๋ฅํ๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ํ์ ์ถ๋ก ์คํจ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ง ์๋๋ค. - KeyPath๋ณ์๋ ReferenceWritableKeyPath๋ก ํ์
์ ์ค์ ํด์ผํ๋ค.
๊ณ์ฐ ์์ฑ์ ์ ๊ทผํ๊ธฐ ๋๋ฌธ์UserDefaults.standard[keyPath: path]์์path๊ฐ ์ฐธ์กฐ ํ์์ด ์๋๋ฉด UserDefaults์์ ์ ์ํ ๊ณ์ฐ ์์ฑ์ get์ ์ ๊ทผํด ์๋ก์ด ๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ ๋๋ฌธ์ด๋ค.
'์ด๋ชจ์ ๋ชจ > Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| WWDC - Async algorithm ํจํค์ง (0) | 2024.10.20 |
|---|---|
| Swift - Task.Sleep vs Timer (0) | 2024.04.30 |
| ios - ์ด๋ฏธ์ง ์ค๋ณต ์ฌ์ฉ ๋ฐฉ์ง ์ฒ๋ฆฌ (0) | 2024.01.25 |
| TaskCounter๋ก ๋ณ๋ ฌ ์์ ์๋ฃ ๊ณ์ ํ์ ํ๊ธฐ (0) | 2023.12.13 |
| UserDefaults with propertyWrapper (0) | 2023.11.30 |
๋๊ธ