Skip to content

Instantly share code, notes, and snippets.

@ohtwo
Last active July 22, 2022 06:30
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 ohtwo/72346c2e616bff93d8c54329dee783b5 to your computer and use it in GitHub Desktop.
Save ohtwo/72346c2e616bff93d8c54329dee783b5 to your computer and use it in GitHub Desktop.
Variable in extension has default value
struct InspectableComponent {
var isHideBackBarButtonTitle = true
}
protocol HasInspectableComponent {
var inspectableComponent: InspectableComponent { get set }
}
protocol InspectableAttribute: HasInspectableComponent { }
extension InspectableAttribute {
var isHideBackBarButtonTitle: Bool {
get { return inspectableComponent.isHideBackBarButtonTitle }
set { inspectableComponent.isHideBackBarButtonTitle = newValue }
}
}
extension UIViewController: InspectableAttribute {
private struct AssociatedKey {
static var inspectableComponent = "UIViewController.inspectableComponent"
}
var inspectableComponent: InspectableComponent {
get {
guard let component = objc_getAssociatedObject(self, &AssociatedKey.inspectableComponent) as? InspectableComponent else {
return InspectableComponent()
}
return component
}
set {
objc_setAssociatedObject(self, &AssociatedKey.inspectableComponent, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment