Skip to content

Instantly share code, notes, and snippets.

@vitorventurin
Created February 13, 2021 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitorventurin/b2aefe20c10a242d32e49977c27048ff to your computer and use it in GitHub Desktop.
Save vitorventurin/b2aefe20c10a242d32e49977c27048ff to your computer and use it in GitHub Desktop.
Stored Properties In Swift Extensions - https://marcosantadev.com/stored-properties-swift-extensions/
import UIKit
protocol PropertyStoring {
associatedtype T
func getAssociatedObject(_ key: UnsafeRawPointer, defaultValue: T) -> T
}
extension PropertyStoring {
func getAssociatedObject(_ key: UnsafeRawPointer, defaultValue: T) -> T {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
}
protocol ToggleProtocol {
func toggle()
}
enum ToggleState {
case on
case off
}
extension UIButton: ToggleProtocol, PropertyStoring {
typealias T = ToggleState
private struct CustomProperties {
static var toggleState = ToggleState.off
}
private(set) var toggleState: ToggleState {
get {
return getAssociatedObject(&CustomProperties.toggleState, defaultValue: CustomProperties.toggleState)
}
set {
objc_setAssociatedObject(self, &CustomProperties.toggleState, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func toggle() {
toggleState = toggleState == .on ? .off : .on
if toggleState == .on {
self.backgroundColor = .green
} else {
self.backgroundColor = .red
}
}
}
let button = UIButton()
print(button.toggleState)
button.toggle()
print(button.toggleState)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment