Skip to content

Instantly share code, notes, and snippets.

@neonichu
Created September 29, 2014 08:17
Show Gist options
  • Save neonichu/36dbf27dc75f0ce166c7 to your computer and use it in GitHub Desktop.
Save neonichu/36dbf27dc75f0ce166c7 to your computer and use it in GitHub Desktop.
How to use imp_implementationWithBlock in Swift
import Foundation
import ObjectiveC.runtime
let myString = "foobar" as NSString
println(myString.description)
let myBlock : @objc_block (AnyObject!) -> String = { (sself : AnyObject!) -> (String) in
"✋"
}
let myIMP = imp_implementationWithBlock(unsafeBitCast(myBlock, AnyObject.self))
let method = class_getInstanceMethod(myString.dynamicType, "description")
method_setImplementation(method, myIMP)
println(myString.description)
@cprovatas
Copy link

cprovatas commented Nov 2, 2017

@objc_block doesn't seem to exist in Swift 4. Any idea what the syntax was changed to?

@JABeachbody
Copy link

@cprovatas Use @convention(block) instead of @objc_block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment