Skip to content

Instantly share code, notes, and snippets.

@WorldDownTown
Last active June 21, 2018 10:46
Show Gist options
  • Save WorldDownTown/4d04ea3a3812bb818522ff3fb25d699b to your computer and use it in GitHub Desktop.
Save WorldDownTown/4d04ea3a3812bb818522ff3fb25d699b to your computer and use it in GitHub Desktop.
An example of Extension based on Kingfisher in Swift.
public final class Extension<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public struct StaticExtension<Base> { }
public protocol ExtensionCompatible {
associatedtype Base
var ex: Extension<Base> { get }
static var ex: StaticExtension<Base> { get }
}
public extension ExtensionCompatible {
public var ex: Extension<Self> {
return Extension(self)
}
public static var ex: StaticExtension<Self> {
return StaticExtension()
}
}
/// Int Extension
extension Int: ExtensionCompatible { }
public extension Extension where Base == Int {
public var cube: Int {
return base * base * base
}
}
public extension StaticExtension where Base == Int {
public var almostMax: Int {
return Int.max - 1
}
}
4.ex.cube // 64
Int.ex.almostMax // 9223372036854775806
/// String Extension
extension String: ExtensionCompatible { }
public extension Extension where Base == String {
public var reversed: String {
return String(base.characters.reversed())
}
}
public extension StaticExtension where Base == String {
public func greet(to name: String) -> String {
return "Hi, \(name)."
}
}
"hello".ex.reversed // olleh
String.ex.greet(to: "Michael") // Hi, Michael.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment