Last active
November 18, 2016 19:35
-
-
Save erica/e3b8ba88b549e786787d to your computer and use it in GitHub Desktop.
This file contains 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
// 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