Last active
May 7, 2019 21:50
-
-
Save amadeu01/6be550165eae6aa2989db4c1d8c6615e to your computer and use it in GitHub Desktop.
Bundle extension with useful swizzling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private func swizzle(_ bundle: Bundle.Type) { | |
| [(#selector(bundle.localizedString(forKey:value:table:)), | |
| #selector(bundle.rd_localizedString(forKey:value:table:)))] | |
| .forEach { original, swizzled in | |
| guard let originalMethod = class_getInstanceMethod(bundle, original), | |
| let swizzledMethod = class_getInstanceMethod(bundle, swizzled) else { return } | |
| let didAddMethod = class_addMethod( | |
| bundle, | |
| original, | |
| method_getImplementation(swizzledMethod), | |
| method_getTypeEncoding(swizzledMethod) | |
| ) | |
| if didAddMethod { | |
| class_replaceMethod( | |
| bundle, | |
| swizzled, | |
| method_getImplementation(originalMethod), | |
| method_getTypeEncoding(originalMethod) | |
| ) | |
| } else { | |
| method_exchangeImplementations(originalMethod, swizzledMethod) | |
| } | |
| } | |
| } | |
| private var hasSwizzled = false | |
| extension Bundle { | |
| final public class func | |
| doBadSwizzleStuff() { | |
| guard !hasSwizzled else { return } | |
| hasSwizzled = true | |
| swizzle(self) | |
| } | |
| @objc internal func rd_localizedString(forKey: String, value: String?, table: String?) -> String { | |
| let bundle = Bundle.main | |
| return bundle.rd_localizedString(forKey: forKey, value: value, table: table) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment