Created
February 13, 2021 13:03
-
-
Save vitorventurin/b2aefe20c10a242d32e49977c27048ff to your computer and use it in GitHub Desktop.
Stored Properties In Swift Extensions - https://marcosantadev.com/stored-properties-swift-extensions/
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
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