Availability checks for SwiftUI

Hello, I'm trying to come up with a nice API for Swiftui availability checks, that all our dev colleagues can easily use.

extension View {
    @ViewBuilder
    func iOSVersionModifiers<iOS15: View, iOS14: View>(iOS15: (Self) -> iOS15, iOS14: (Self) -> iOS14) -> some View {
        if #available(iOS 15.0, *) {
            iOS15(self)
        } else {
            iOS14(self)
        }
    }

    func iOS15Modifiers<iOS15: View>(_ iOS15: (Self) -> iOS15) -> some View {
        iOSVersionModifiers(iOS15: iOS15, iOS14: { _ in self })
    }

    func iOS14Modifiers<iOS14: View>(_ iOS14: (Self) -> iOS14) -> some View {
        iOSVersionModifiers(iOS15: { _ in self }, iOS14: iOS14)
    }
}

Usage:

TextField("Search", text: $viewModel.searchText)
    .iOSVersionModifiers {
        $0.submitLabel(.search) // Error: 'submitLabel' is only available in iOS 15.0 or newer
    } iOS14: {
        $0.introspectTextField(customize: { $0.returnKeyType = .search })
    }

When I try to use the following snippet, I always get a compile-time error. I think I understand why that's the case, even though I don't agree with it, but can anyone point me in the right direction going forward?

I suggest you read this thread!

1 Like

thanks!

Terms of Service

Privacy Policy

Cookie Policy