'How can I infer a PreferenceKey in SwiftUI?

This code works fine, I want infer PreferenceKey there:

extension View {
        func onPreference<K: PreferenceKey>(key: K.Type, value: K.Value, action: @escaping (K.Value) -> Void) -> some View where K.Value: Equatable {
            return self
                .preference(key: key, value: value)
                .onPreferenceChange(key, perform: { newValue in action(newValue) })
        }
    }

struct CGSizePreferenceKey: PreferenceKey {
    
    static var defaultValue: CGSize { get { return CGSize() } }
    
    static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
    
}

Here is what I tried so far:

extension View {
    func onPreferenceCGSizePreferenceKey<K: PreferenceKey>(value: K.Value, action: @escaping (K.Value) -> Void) -> some View where K.Value: Equatable, K.Type == CGSizePreferenceKey  {
        return self
            .preference(key: K.self, value: value)
            .onPreferenceChange(K.self, perform: { newValue in action(newValue) })
    }
}

The error:

Generic signature requires types 'K.Type' and 'CGSizePreferenceKey' to be the same



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source