Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Created January 16, 2023 23:55
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 katsuyoshi/51039a6fd878d74a499f07a1890a116f to your computer and use it in GitHub Desktop.
Save katsuyoshi/51039a6fd878d74a499f07a1890a116f to your computer and use it in GitHub Desktop.
objcで [[self class] new] とするのを Swift で
Hello, I'm an instance of A.
Hello, I'm an instance of A.
Hello, I'm an instance of B.
Hello, I'm an instance of B.
class A {
// required を付けた init() が必要
required init() {}
func hello() {
print("Hello, I'm an instance of A.")
}
func newInstance() -> A {
return type(of: self).init()
}
}
class B: A {
override func hello() {
print("Hello, I'm an instance of B.")
}
}
let a = A()
let a2 = a.newInstance()
let b = B()
let b2 = b.newInstance()
a.hello()
a2.hello()
b.hello()
b2.hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment