Skip to content

Instantly share code, notes, and snippets.

@MrSmart00
Last active January 23, 2019 09:22
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 MrSmart00/996c7048e4c204a4de7808e1fd871b11 to your computer and use it in GitHub Desktop.
Save MrSmart00/996c7048e4c204a4de7808e1fd871b11 to your computer and use it in GitHub Desktop.
How to use a Modern swifty extensions
let view = UIView(frame: .zero)
print(view.description) // <UIView: 0x7fd6dc500640; frame = (0 0; 0 0); layer = <CALayer: 0x60000390b7c0>>
print(view.my.description) // HOGE FUGA : (0.0, 0.0, 0.0, 0.0)
print(UIView.my.description) // I AM UIView
let label = UILabel(frame: .zero)
label.text = "test"
print(label.description) // <UILabel: 0x7fad33e06870; frame = (0 0; 0 0); text = 'test'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x6000019c3660>>
print(label.my.description) // FUGA HOGE : Optional("test")
print(UILabel.my.description) // I AM UILabel
public class MyExtension<T> {
let obj: T
public init(base: T) {
self.obj = base
}
}
public protocol MyExtensionObject {
associatedtype ExtensionType
static var my: ExtensionType.Type { get }
var my: ExtensionType { get }
}
public extension MyExtensionObject {
// For Static Property
public static var my: MyExtension<Self>.Type {
return MyExtension<Self>.self
}
// For Instance Property
public var my: MyExtension<Self> {
return MyExtension(base: self)
}
}
/// UILabel adopted MyExtensionObject
extension UILabel: MyExtensionObject {}
extension MyExtension where T: UILabel {
/// Caution: Here is in MyExtension, not UILabel
var description: String {
return "FUGA HOGE : \(obj.text)"
}
static var description: String {
return "I AM UILabel"
}
}
/// UIView adopted MyExtensionObject
extension UIView: MyExtensionObject {}
extension MyExtension where T: UIView {
/// Caution: Here is in MyExtension, not UIView
var description: String {
return "HOGE FUGA : \(obj.frame)"
}
static var description: String {
return "I AM UIView"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment