Created
January 16, 2023 23:55
-
-
Save katsuyoshi/51039a6fd878d74a499f07a1890a116f to your computer and use it in GitHub Desktop.
objcで [[self class] new] とするのを Swift で
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
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. |
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
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