Swift function swizzling / runtime

后端 未结 8 1263
自闭症患者
自闭症患者 2020-12-05 08:04

Before Swift, in Objective-C I would swizzle or hook methods in a class using .

If anyone has any info on the topic of modifying S

8条回答
  •  一生所求
    2020-12-05 08:20

    I would like to extend the great answer provided by mbazaliy.

    Another way of doing swizzling in Swift is by providing an implementation using an Objective-C block.

    e.g. to replace descriptionmethod on class NSString we can write:

    let originalMethod = class_getInstanceMethod(NSString.self, "description")
    
    let impBlock : @objc_block () -> NSString =
            { () in return "Bit of a hack job!" }
    
    let newMethodImp = imp_implementationWithBlock(unsafeBitCast(impBlock, AnyObject.self))
    
    method_setImplementation(originalMethod, newMethodImp)
    

    This works as of Swift 1.1.

提交回复
热议问题