Search code examples
swiftmigrationmethod-swizzling

Port method swizzle of NSLocale.currentLocale from swift 2.3 to swift 3


Swift 3 introduced a lot of changes in the NSLocale(now Locale) class. I need to perform method swizzle of NSLocale.currentLocale() to perform Unit test of some helpers. With Swift 2.3 I could use this method:

extension NSLocale {
    @nonobjc static var ttt_locale = "us_US"
    @nonobjc static var ttt_swizzled = false

    class func customizedLocale()->NSLocale{
        return NSLocale(localeIdentifier: NSLocale.ttt_locale)
    }

    class func forceLocale(identifier:String){
        NSLocale.ttt_locale = identifier

        if !NSLocale.ttt_swizzled {
            NSLocale.ttt_swizzled = true
            let originalSelector = #selector(NSLocale.currentLocale)
            let swizzledSelector = #selector(self.customizedLocale)

            let originalMethod = class_getClassMethod(self, originalSelector)
            let swizzledMethod = class_getClassMethod(self, swizzledSelector)

            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
} 

The problem now is that with Swift 3 currentLocale is no longer though and it has been substituted with the property current.

How could achieve the same result with Swift 3?


Solution

  • current is a (read-only) computed property of NSLocale:

    open class var current: Locale { get }
    

    You build a selector for Objectice-C property getter with

    let originalSelector = #selector(getter: NSLocale.current)
    

    See also SE-0064 Referencing the Objective-C selector of property getters and setters.