Skip to content

Instantly share code, notes, and snippets.

@omochi
Created June 21, 2019 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omochi/f746fc8db92ce0482e19ab313a2f6c6b to your computer and use it in GitHub Desktop.
Save omochi/f746fc8db92ce0482e19ab313a2f6c6b to your computer and use it in GitHub Desktop.
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