Swift interoperability with category on NSLocale

I have a mixed Swift/Objective-C project with a category on NSLocale defining (among others):


- (NSString*)extendedLanguageCode;


I used to access this method in Swift like this:


Locale.current.extendedLanguageCode()


In Xcode 8 beta 4 this no longer works and I have to cast Locale back to NSLocale:


(Locale.current as NSLocale).extendedLanguageCode()


Is this the intended behavior? If yes, I don't like it!

Accepted Reply

I'd be fine to simply use NSLocale in Swift but this doesn't work either:

Right.

NSLocale.current
is returning a value of type
Locale
, which is a bit strange but there you go (-:

If I'd convert my NSLocale category to a Swift extension to Locale, can I then still use it from Objective-C code as NSLocale?

No. As I mentioned earlier, they are two separate types. However, you can have your Swift code call your Objective-C very easily.

extension Locale {
    var extendedLanguageCode: String {
        return (self as NSLocale).extendedLanguageCode()
    }
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

Yes, that’s expected behaviour.

Locale
and
NSLocale
are separate types and thus a category on one doesn’t translate to an extension on the other.

Why don’t you add your own Swift extension to

Locale
?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I'd be fine to simply use NSLocale in Swift but this doesn't work either:


NSLocale.current.extendedLanguageCode()


fails with "Value of type 'Locale' has no member extendedLanguageCode". So Swift seems to translate NSLocale to Locale behind the scenes.


If I'd convert my NSLocale category to a Swift extension to Locale, can I then still use it from Objective-C code as NSLocale?

I'd be fine to simply use NSLocale in Swift but this doesn't work either:

Right.

NSLocale.current
is returning a value of type
Locale
, which is a bit strange but there you go (-:

If I'd convert my NSLocale category to a Swift extension to Locale, can I then still use it from Objective-C code as NSLocale?

No. As I mentioned earlier, they are two separate types. However, you can have your Swift code call your Objective-C very easily.

extension Locale {
    var extendedLanguageCode: String {
        return (self as NSLocale).extendedLanguageCode()
    }
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"