Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protocol HasInit {
- init()
- func sayHi()
- }
- extension HasInit {
- func sayHi() { print("Hi from an instance of \(type(of: self))") }
- }
- class A:HasInit {
- required init() { print("Init of \(type(of: self))") }
- }
- func makeInstance<T>(_ thetype:T.Type ) -> HasInit? {
- return (thetype as? HasInit.Type)?.init()
- }
- let aClassType = A.self
- let aInstance = aClassType.init()
- aInstance.sayHi()
- let aaClass = type(of: aInstance)
- makeInstance(aaClass)?.sayHi()
- struct AS:HasInit {
- init() { print("Init of \(type(of: self))") }
- }
- let asStructType = AS.self
- let asInstance = asStructType.init()
- asInstance.sayHi()
- makeInstance(type(of: asInstance))?.sayHi()
Add Comment
Please, Sign In to add comment