Skip to content

Instantly share code, notes, and snippets.

@erica
Last active Nov 18, 2016
Embed
What would you like to do?
// 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