Created
March 21, 2017 10:54
-
-
Save vlondon/e0fcb728c6a963e31b288adb79dbfc22 to your computer and use it in GitHub Desktop.
Swizzling in Swift 3
This file contains 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
import Foundation | |
// Swizzling | |
extension NSObject { | |
class func swizzleMethods(origSelector: Selector, withSelector: Selector, forClass: AnyClass) { | |
let originalMethod = class_getInstanceMethod(forClass, origSelector) | |
let swizzledMethod = class_getInstanceMethod(forClass, withSelector) | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
func swizzleMethods(origSelector: Selector, withSelector: Selector) { | |
let aClass: AnyClass! = object_getClass(self) | |
NSObject.swizzleMethods(origSelector: origSelector, withSelector: withSelector, forClass: aClass) | |
} | |
} |
This file contains 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
import UIKit | |
// Use Swizzling | |
public extension UIColor { | |
func colorDescription() -> String { | |
return "Some Custom text Here" | |
} | |
public class func swizzleDesription() { | |
let instance = UIColor.red | |
instance.swizzleMethods(origSelector: #selector(UIColor.colorDescription), withSelector: #selector(getter: NSObjectProtocol.description)) | |
} | |
} | |
// Somewhere in the Project | |
UIColor.swizzleDesription() | |
print(UIColor.red) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment