Skip to content

Instantly share code, notes, and snippets.

@amadeu01
Last active May 7, 2019 21:50
Show Gist options
  • Save amadeu01/6be550165eae6aa2989db4c1d8c6615e to your computer and use it in GitHub Desktop.
Save amadeu01/6be550165eae6aa2989db4c1d8c6615e to your computer and use it in GitHub Desktop.
Bundle extension with useful swizzling
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