Using of UITraitBridgedEnvironmentKey inside Backyard Birds

Hi, I have a question regarding the use of UITraitBridgedEnvironmentKey inside the example project of Backyard Birds.

It seems to me that there isn't a reason to use that protocol because we are not synching the UIKit and SwiftUI keys. Moreover, inside the extension, we use that protocol only to get the UITraitCollection to identify if is a phone or tv.

Here is the Backyard Birds code to better clarify:

// File: PrefersTabNavigationEnvironmentKey

struct PrefersTabNavigationEnvironmentKey: EnvironmentKey {
    static var defaultValue: Bool = false
}

extension EnvironmentValues {
    var prefersTabNavigation: Bool {
        get { self[PrefersTabNavigationEnvironmentKey.self] }
        set { self[PrefersTabNavigationEnvironmentKey.self] = newValue }
    }
}

#if os(iOS)
extension PrefersTabNavigationEnvironmentKey: UITraitBridgedEnvironmentKey {
    static func read(from traitCollection: UITraitCollection) -> Bool {
       return traitCollection.userInterfaceIdiom == .phone || traitCollection.userInterfaceIdiom == .tv
 }
 
    static func write(to mutableTraits: inout UIMutableTraits, value: Bool) {
        // Do not write.
    }
}
#endif

I think that the extension PrefersTabNavigationEnvironmentKey is useless because if I want to know the userInterfaceIdiom I can use the UIDevice.current.userInterfaceIdiom. Moreover the set method inside prefersTabNavigation is useless too because I will never write the prefersTabNavigation.

I re-write the class in this way:

struct PrefersTabNavigationEnvironmentKey: EnvironmentKey {
    static var defaultValue: Bool = false
}

extension EnvironmentValues {
    var prefersTabNavigation: Bool {
        get { UIDevice.current.userInterfaceIdiom == .phone || UIDevice.current.userInterfaceIdiom == .tv }
//set { self[PrefersTabNavigationEnvironmentKey.self] = newValue } --> remove that
    }
}

Is it correct or I'm missing something?

Thank you in advance

Replies

Moreover, I noticed that we can remove PrefersTabNavigationEnvironmentKey too

The code will become:

extension EnvironmentValues {
    var prefersTabNavigation: Bool {
        get { UIDevice.current.userInterfaceIdiom == .phone || UIDevice.current.userInterfaceIdiom == .tv }
    }
}