Extensions Wrapper
Swift
Read the blog post.
swift
public struct ExtensionsWrapper<Base> {
public var base: Base
public init(_ base: Base) {
self.base = base
}
}
swift
public protocol ExtensionsCompatible {
associatedtype CompatibleType
static var ext: ExtensionsWrapper<CompatibleType>.Type { get set }
var ext: ExtensionsWrapper<CompatibleType> { get set }
}
extension ExtensionsCompatible {
public var ext: ExtensionsWrapper<Self> {
get {
return ExtensionsWrapper(self)
}
set {}
}
public static var ext: ExtensionsWrapper<Self>.Type {
get {
return ExtensionsWrapper<Self>.self
}
set {}
}
}
Usage example
extension UILabel: ExtensionsCompatible {}
extension ExtensionsWrapper where Base: UILabel {
public var trimmedText: String? {
let aText = base.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if aText.isEmpty { return nil }
return aText
}
}
let label = UILabel()
label.text = " Hello. "
print(someLabel.ext. trimmedText) // prints "Hello."