Guest User

Untitled

a guest
Oct 20th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.65 KB | None | 0 0
  1. protocol HasInit {
  2. init()
  3. func sayHi()
  4. }
  5.  
  6. extension HasInit {
  7. func sayHi() { print("Hi from an instance of \(type(of: self))") }
  8. }
  9.  
  10. class A:HasInit {
  11. required init() { print("Init of \(type(of: self))") }
  12. }
  13.  
  14. func makeInstance<T>(_ thetype:T.Type ) -> HasInit? {
  15. return (thetype as? HasInit.Type)?.init()
  16. }
  17.  
  18.  
  19. let aClassType = A.self
  20. let aInstance = aClassType.init()
  21. aInstance.sayHi()
  22. let aaClass = type(of: aInstance)
  23. makeInstance(aaClass)?.sayHi()
  24.  
  25.  
  26. struct AS:HasInit {
  27. init() { print("Init of \(type(of: self))") }
  28. }
  29. let asStructType = AS.self
  30. let asInstance = asStructType.init()
  31. asInstance.sayHi()
  32. makeInstance(type(of: asInstance))?.sayHi()
Add Comment
Please, Sign In to add comment