'How can I inferring PreferenceKey/PreferenceKey.Type in Swift/SwiftUI?
This below code was my previous question and it is working, since I am not using key parameter directly I want try to remove it from function and possibly infer it,
extension View {
func onPreference<K: PreferenceKey>(key: K.Type, value: K.Value, action: ((K.Value) -> Void)?) -> some View where K.Value: Equatable {
return self
.preference(key: K.self, value: value)
.onPreferenceChange(K.self, perform: { newValue in action?(newValue)})
}
}
For making my goal possible I want build an array that cover all types that i am going use them in function, like Bool, Int and CGSize, I really do not know if it is good idea to make such function or even if it is a thing in swift or swiftUI, these below code are just pseudocode, I am unable code to solve the issues or problems, need help there
Also if you think using an array is not possible may I should work on switch or if let inside function.
I want add that the goal of inferring is stopping making and repeating code for each Keys. Which with given value to function, the function would be understand which key needed to make codes works.
extension View {
func onPreference<K: PreferenceKey, V: Equatable>(value: V, action: @escaping (V) -> Void) -> some View where V == K.Value, K.defaultValue == arrayOfKeys[?].defaultValue {
return self
.preference(key: K.self, value: value)
.onPreferenceChange(K.self, perform: { newValue in action(newValue)})
}
}
let arrayOfKeys: Array<PreferenceKey> = [BoolPreferenceKey, IntPreferenceKey, CGSizePreferenceKey]
struct BoolPreferenceKey: PreferenceKey {
static var defaultValue: Bool { get { return Bool() } }
static func reduce(value: inout Bool, nextValue: () -> Bool) { value = nextValue() }
}
struct IntPreferenceKey: PreferenceKey {
static var defaultValue: Int { get { return Int() } }
static func reduce(value: inout Int, nextValue: () -> Int) { value = nextValue() }
}
struct CGSizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize { get { return CGSize() } }
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
