-
-
Save koher/fdddb76694ea9e7cc270e9710b4b0ef3 to your computer and use it in GitHub Desktop.
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
protocol CatProtocol { | |
var name: String { get set } | |
func nya() -> String | |
mutating func sleep() | |
func clone() -> Self | |
func cast<T>(to: T.Type) -> T? | |
} | |
class Cat : CatProtocol { | |
required init() {} | |
var name: String = "tama" | |
func nya() -> String { return "nyaaaa" } | |
func sleep() { print("zzz...") } | |
func clone() -> Self { | |
return type(of: self).init() | |
} | |
func cast<T>(to: T.Type) -> T? { | |
return self as? T | |
} | |
} | |
struct AnyCat1 : CatProtocol { | |
init<X: CatProtocol>(_ x: X) { | |
var x = x | |
_getName = { x.name } | |
_setName = { x.name = $0 } | |
_nya = { x.nya() } | |
_sleep = { x.sleep() } | |
_clone = { AnyCat1(x.clone()) } | |
_cast = { (to: Any.Type) -> Any? in | |
print(type(of: to)) | |
return nil | |
//return x.cast(to: to) | |
} | |
} | |
var name: String { | |
get { return _getName() } | |
set { _setName(newValue) } | |
} | |
func nya() -> String { | |
return _nya() | |
} | |
func sleep() { _sleep() } | |
func clone() -> AnyCat1 { | |
return _clone() | |
} | |
func cast<T>(to: T.Type) -> T? { | |
return _cast(to) as? T | |
} | |
var _getName: () -> String | |
var _setName: (String) -> Void | |
var _nya: () -> String | |
var _sleep: () -> Void | |
var _clone: () -> AnyCat1 | |
var _cast: (Any.Type) -> Any? | |
} | |
let a = AnyCat1(Cat()) | |
print(String(describing: a.cast(to: String.self))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment