Last active
March 5, 2022 03:10
-
-
Save WorldDownTown/3e0ac74b0add9b22f9188421de608d1a to your computer and use it in GitHub Desktop.
An example of Extension based on RxSwift 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 struct Extension<Base> { | |
public let base: Base | |
public init(_ base: Base) { | |
self.base = base | |
} | |
} | |
public protocol ExtensionCompatible { | |
associatedtype Compatible | |
var ex: Extension<Compatible> { get set } | |
static var ex: Extension<Compatible>.Type { get set } | |
} | |
public extension ExtensionCompatible { | |
public var ex: Extension<Self> { | |
get { | |
return Extension(self) | |
} | |
set { | |
// this enables using Extension to "mutate" base object | |
} | |
} | |
public static var ex: Extension<Self>.Type { | |
get { | |
return Extension<Self>.self | |
} | |
set { | |
// this enables using Extension to "mutate" base type | |
} | |
} | |
} | |
/// Int Extension | |
extension Int: ExtensionCompatible { } | |
public extension Extension where Base == Int { | |
public var cube: Int { | |
return base * base * base | |
} | |
public static 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 static 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