Skip to content

Instantly share code, notes, and snippets.

@muizidn
Created December 21, 2017 03:14
Show Gist options
  • Save muizidn/d38c5f69e2269cfa3ce33c901cb78698 to your computer and use it in GitHub Desktop.
Save muizidn/d38c5f69e2269cfa3ce33c901cb78698 to your computer and use it in GitHub Desktop.
A declaration which used when user wants to put stored property in extension
protocol PropertyStoring {
func getAssociatedObject<T>(_ key: UnsafeRawPointer, defaultValue: T) -> T
}
extension PropertyStoring {
func getAssociatedObject<T>(_ key: UnsafeRawPointer, defaultValue: T) -> T {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
}
// Example
extension UIButton: PropertyStoring {
fileprivate CustomProperty {
static var tapCount = 0
}
var tapCount: Int {
get {
return getAssociatedObject(&CustomProperty.tapCount, defaultValue: CustomProperty.tapCount)
}
set {
return objc_setAssociatedObject(self, &CustomProperty.tapCount, newValue, .OBJC_ASSOCIATION_RETAIN )
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment