Created
June 21, 2019 09:11
-
-
Save omochi/f746fc8db92ce0482e19ab313a2f6c6b 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 CopyInitializable {} | |
extension CopyInitializable { | |
init(copy: Self) { self = copy } | |
} | |
class Animal : CopyInitializable { | |
init() {} | |
convenience init(a: Int) { | |
let copy = Animal() | |
// `Self`にforce castしたいがここに`Self`が書けないので | |
// self.init(copy: copy as! Self) | |
// type(of: self)でSelf型を作って、 | |
// それをジェネリクスに渡すことで`as!`を実行できる | |
self.init(copy: forceCast(copy, to: type(of: self))) | |
} | |
} | |
func forceCast<X, T>(_ x: X, to type: T.Type) -> T { return x as! T } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment