Joey Joey - 11 months ago 55
Swift Question

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

and it returns a
. 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
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?

Answer Source

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()