Basics of Swift Swizzling

suggest change

Let’s swap the implementation of methodOne() and methodTwo() in our TestSwizzling class:

class TestSwizzling : NSObject {
    @objc dynamic func methodOne() -> Int {
        return 1
    }
}

extension TestSwizzling {
    
    // Objective-C often swizzles in +load or +initialize.
    // Swift does not allow either method, so call `swizzle()` once yourself.
    static func swizzle() {
        struct Inner {
            static let i: Void = {
                let originalSelector = #selector(TestSwizzling.methodOne)
                let swizzledSelector = #selector(TestSwizzling.methodTwo)
                guard let originalMethod = class_getInstanceMethod(TestSwizzling.self, originalSelector),
                      let swizzledMethod = class_getInstanceMethod(TestSwizzling.self, swizzledSelector) else {
                    return
                }
                method_exchangeImplementations(originalMethod, swizzledMethod)
            }()
        }
        _ = Inner.i
    }

    @objc dynamic func methodTwo() -> Int {
        // After the exchange this calls the original methodOne and adds 1.
        return methodTwo() + 1
    }
}

TestSwizzling.swizzle()
let c = TestSwizzling()
print(c.methodOne())
print(c.methodTwo())

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents