Last active
          June 5, 2020 15:32 
        
      - 
      
- 
        Save ncreated/ccf68aea1061a923e63346a70486ed52 to your computer and use it in GitHub Desktop. 
    Object-oriented method swizzling
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | private class Locker {} | |
| private let locker = Locker() | |
| internal class Method { | |
| static func `for`(selector: Selector, inClass `class`: AnyClass) -> Method? { | |
| objc_sync_enter(locker) | |
| if let existingSwizzling = existingSwizzlings[hash(class, selector]) { | |
| return existingSwizzlings | |
| } | |
| let newSwizzling = Method(method: method) | |
| existingSwizzlings[hash(class, selector)] = newSwizzling | |
| objc_sync_exit(locker) | |
| return newSwizzling | |
| } | |
| func set(newImplementation newIMP: IMP) { | |
| objc_sync_enter(locker) | |
| // do the thing | |
| objc_sync_exit(locker) | |
| } | |
| } | |
| private var existingSwizzlings: [hash(class, selector): Method] = [:] | 
  
    
      This file contains hidden or 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
    
  
  
    
  | internal class Method { | |
| static func `for`(selector: Selector, inClass `class`: AnyClass) -> Method? { | |
| if let existingSwizzling = existingSwizzlings[hash(class, selector]) { | |
| return existingSwizzlings | |
| } | |
| let newSwizzling = Method(method: method) | |
| existingSwizzlings[hash(class, selector)] = newSwizzling | |
| return newSwizzling | |
| } | |
| func set(newImplementation newIMP: IMP) { | |
| // do the thing | |
| } | |
| } | |
| private var existingSwizzlings: [hash(class, selector): Method] = [:] | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment