Skip to content

Instantly share code, notes, and snippets.

@wleii
Created April 27, 2018 10:04
Show Gist options
  • Save wleii/44dad73a53076216c71b6834a7518960 to your computer and use it in GitHub Desktop.
Save wleii/44dad73a53076216c71b6834a7518960 to your computer and use it in GitHub Desktop.
easy use as/is function at function-chain
protocol Asable {
func `as`<T>(_ anyType: T.Type) -> T?
func `is`<T>(_ anyType: T.Type) -> Bool
}
extension Asable {
func `as`<T>(_ anyType: T.Type) -> T? {
return self as? T
}
func `is`<T>(_ anyType: T.Type) -> Bool {
return self is T
}
}
struct A {
func testA() -> String { return "this is A"}
}
struct B {}
extension A: Asable {}
extension B: Asable {}
let a = A()
a.as(A.self)?.testA()
a.is(A.self)
a.is(B.self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment