UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Why is this written this way: func preference<K>(key _: K.Type = K.self, value: K.Value) -> some View where K : PreferenceKey

Forums > SwiftUI

With that key default?

func preference<K>(key _: K.Type = K.self, value: K.Value) -> some View where K : PreferenceKey

I can see no way to write code that omits the key parameter because I don't see how the compiler can infer K from value: K.Value. The key param is only for type info and not used iside the func as its name is _.

Same issue with these:

func anchorPreference<A, K>(key _: K.Type = K.self, value: Anchor<A>.Source, transform: @escaping (Anchor<A>) -> K.Value) -> some View where K : PreferenceKey
func onPreferenceChange<K>(_ key: K.Type = K.self, perform action: @escaping (K.Value) -> Void) -> some View where K : PreferenceKey, K.Value : Equatable
func overlayPreferenceValue<Key, T>(_ key: Key.Type = Key.self, @ViewBuilder _ transform: @escaping (Key.Value) -> T) -> some View where Key : PreferenceKey, T : View
func backgroundPreferenceValue<Key, T>(_ key: Key.Type = Key.self, @ViewBuilder _ transform: @escaping (Key.Value) -> T) -> some View where Key : PreferenceKey, T : View

if you omit key, there is no way the compiler can infer K from knowing only K.Value

See https://forums.swift.org/t/swiftui-anchorpreference-a-k-key-k-type-k-self-how-to-make-use-of-key-params-default-value/35081

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.