1

With Swift 2, Apple introduced the API availability checking which allows one to execute certain code only on a specified version or later, like this:

if #available(iOS 9, *) {
    // use UIStackView
} else {
    // use fallback
}

For instance, iOS 9.0 introduces the localizedUppercaseString property:

/// An uppercase version of the string that is produced using the current
/// locale.
public var localizedUppercaseString: String { get }

What I want is to create an exact replica of this property that is only available for versions lower than 9.0 so I do not have to check if #available(iOS 9, *) whenever I need to use this (or any other) property/method.

The best result I could get was the following:

extension String {

    @available(iOS 8.0, *)
    var localizedUppercaseString: String {

        return uppercaseStringWithLocale(NSLocale.currentLocale())
    }
}

With this, I can call localizedUppercaseString, no matter if the iOS version is 8.0 or 9.0. The problem is that this extension overrides the "original" property when executed with iOS 9.0.

Renato Rodrigues
  • 1,038
  • 1
  • 18
  • 35

1 Answers1

2
extension String {

    var myLocalizedUppercaseString: String {
        if #available(iOS 9, *) {
            return localizedUppercaseString
        } else {
            return uppercaseStringWithLocale(NSLocale.currentLocale())
        }
    }
}

Now you just have to use myLocalizedUppercaseString property.

Andriy Gordiychuk
  • 6,163
  • 1
  • 24
  • 59
  • This is a good answer. If you are overriding the original localizedUppercaseString there's no way to get a localizedUppercaseString unless you implement it yourself, so you will need to use a custom instance var like @andriygordiychuk has suggested, or be comfortable with your own overriden implementation. – Joseph Quigley Nov 03 '15 at 18:56
  • I was trying to avoid this solution as my intent is to use the "same" property, rather than a custom property. – Renato Rodrigues Nov 04 '15 at 09:37