Last active
June 21, 2018 10:46
-
-
Save WorldDownTown/4d04ea3a3812bb818522ff3fb25d699b to your computer and use it in GitHub Desktop.
An example of Extension based on Kingfisher in Swift.
This file contains 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
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