Skip to content

Instantly share code, notes, and snippets.

@erica
Last active November 18, 2016 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/e3b8ba88b549e786787d to your computer and use it in GitHub Desktop.
Save erica/e3b8ba88b549e786787d to your computer and use it in GitHub Desktop.
// NSObject Nametag
public var sharedNametagKey : UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.alloc(1)
public extension NSObject {
public var nametag: String? {
get {
return objc_getAssociatedObject(self, &sharedNametagKey) as? String
}
set {
if let newNameTag = newValue {
// Store unwrapped new value
objc_setAssociatedObject(self, &sharedNametagKey, newNameTag, .OBJC_ASSOCIATION_RETAIN)
} else {
// Remove by assignment to nil
objc_setAssociatedObject(self, &sharedNametagKey, nil, .OBJC_ASSOCIATION_RETAIN)
}
}
}
}
// Better cast
// Thanks Mike Ash
infix operator --> {}
func --><T, U>(value: T, target: U.Type) -> U? {
guard sizeof(T.self) == sizeof(U.self) else {return nil}
return unsafeBitCast(value, target)
}
// Set and get
func getNametag<T>(castable: T) -> String? {
guard let myObject = castable --> NSObject.self else {return nil}
return myObject.nametag
}
func setNametag<T>(castable: T, tag: String?) {
guard let myObject = castable --> NSObject.self else {
print("Unable to cast")
return
}
myObject.nametag = tag
}
// Original test case
typealias BillTheTypeCat = @convention(block)(item: Int) -> ()
var myBlock: BillTheTypeCat = {_ in print("notSureWhat")}
setNametag(myBlock, tag: "Hello")
print(getNametag(myBlock) ?? "Eh?")
setNametag(myBlock, tag: nil)
print(getNametag(myBlock) ?? "Eh?")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment