Search code examples
iosswiftuiaccessibility

Check if a function is available in Swift?


I would like to detect if the user has enabled Reduce Transparency. It's simple you just call the func UIAccessibilityIsReduceMotionEnabled() and it returns a Bool. But my app targets iOS 7 and 8 and this function isn't available on iOS 7.

In Objective-C, this is how I checked to see if that function exists:

if (UIAccessibilityIsReduceMotionEnabled != NULL) { }

In Swift, I can't figure out how to check if it exists or not. According to this answer, you can simply use optional chaining and if it's nil then it doesn't exist, but that is restricted to Obj-C protocols apparently. Xcode 6.1 doesn't like this:

let reduceMotionDetectionIsAvailable = UIAccessibilityIsReduceMotionEnabled?()

It wants you to remove the ?. And of course if you do so it will crash on iOS 7 because that function doesn't exist.

What is the proper way to check if these types of functions exist?


Solution

  • A proper check for availability has been added in Swift 2. This is recommended over other options mentioned here.

    var shouldApplyMotionEffects = true
    if #available(iOS 8.0, *) {
        shouldApplyMotionEffects = !UIAccessibilityIsReduceMotionEnabled()
    }