์ด๋ชจ์ ๋ชจ/Swift
Property Wrapper With Keypath
ARpple
2023. 8. 21. 20:11
๐ก ์ ์ ๋ํดํธ์ ํน์ ํค(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์ ์ ๊ทผํด ์๋ก์ด ๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ ๋๋ฌธ์ด๋ค.