Created
December 21, 2017 03:14
-
-
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
This file contains hidden or 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
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