Search code examples
iosswiftuiaccessibilityuiaccessibility

Swift: @available up to specific iOS version but not higher


Problem:

I'd like to use accessibilityIdentifier() in SwiftUI on iOS 14, but some of the code supports iOS 13+.

Can I keep using the same API as the iOS 14+ version which will do nothing on iOS 13?

e.g.:

/// How to make this available on pre-iOS 14 only?
extension View {
    func accessibilityIdentifier(_ identifier: String) -> some View {
        if #available(iOS 14.0, macOS 11.0, *) {
                .accessibilityIdentifier(identifier)
        } else {
            self
        }
    }
}


Solution

  • A possible approach is to create own wrapper, like (tested with Xcode 13.2)

    extension View {
        @ViewBuilder
        func accessibility(id identifier: String) -> some View {
            if #available(iOS 14.0, macOS 11.0, *) {
                self.accessibilityIdentifier(identifier)
            } else {
                self.accessibility(identifier: identifier)
            }
        }
    }