Joey Joey - 1 year ago 77
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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download