How can I change the locale on the Xcode Playground
Asked Answered
M

2

15

I'd like to change the locale on the Xcode Playground to test localization.

I found this solution, but it doesn't work on the Xcode 6.3.2 Playground: http://natashatherobot.com/locale-playground-swift/

Maw answered 26/6, 2015 at 5:52 Comment(0)
M
23

Oh, I've found a solution!

extension NSLocale {
    class func mono_currentLocale() -> NSLocale {
        return NSLocale(localeIdentifier: "fr")
    }
}
let original = class_getClassMethod(NSLocale.self, #selector(getter: NSLocale.currentLocale))
let swizzled = class_getClassMethod(NSLocale.self, #selector(NSLocale.mono_currentLocale))
method_exchangeImplementations(original, swizzled)

EDIT: Swift 4.1 version:

extension NSLocale {
    @objc class func mono_currentLocale() -> NSLocale {
        return NSLocale(localeIdentifier: "fr")
    }
}
let original = class_getClassMethod(NSLocale.self, #selector(getter: NSLocale.current))!
let swizzled = class_getClassMethod(NSLocale.self, #selector(NSLocale.mono_currentLocale))!
method_exchangeImplementations(original, swizzled)
Maw answered 26/6, 2015 at 6:9 Comment(1)
Worth noting that Swift 2.2 introduces the new #selector syntax. swift.org/blog/swift-2-2-new-featuresDisorientate
S
5

XCode 13 / Swift 5

To change the current locale in the playground you can create extension of NSLocale and override currentLocale:

extension NSLocale {
    @objc
    static let currentLocale = NSLocale(localeIdentifier: "en_GB") // Set a needed locale
}

let formatter = NumberFormatter()
formatter.numberStyle = .currency
let text = formatter.string(from: 12345.67 as NSNumber)!
print(text)

Outputs:

£12,345.67

NOTE: It also works with unit tests.

Sharynshashlik answered 19/3, 2022 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.