Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.