让我们交换的实现methodOne(),并methodTwo()在我们的TestSwizzling类:
class TestSwizzling : NSObject { dynamic func methodOne()->Int{ return 1 } } extension TestSwizzling { //在Objective-C中,您需要在load()中执行扫描, //但是Swift中不允许使用此方法 override class func initialize() { struct Inner { static let i: () = { let originalSelector = #selector(TestSwizzling.methodOne) let swizzledSelector = #selector(TestSwizzling.methodTwo) let originalMethod = class_getInstanceMethod(TestSwizzling.self, originalSelector); let swizzledMethod = class_getInstanceMethod(TestSwizzling.self, swizzledSelector) method_exchangeImplementations(originalMethod, swizzledMethod) } } let _ = Inner.i } func methodTwo()->Int{ // 混乱后不再是递归调用 return methodTwo()+1 } } var c = TestSwizzling() print(c.methodOne()) print(c.methodTwo())