1

Consider the following code:

var med: Med = Med()

var cls1 = type(of:med)
var cls2 = Med.self
var cls3: AnyClass = Med.self

var med1 = cls1.init()
var med2 = cls2.init()
var med3 = cls3.init() // Compiler: 'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type

The way of doing this seems to have changed a lot between each version of Swift and so searches online provide lots of dead ends.

If Med.self is not of type AnyClass why doesn't the compiler complain when I set cls3? If it is of type AnyClass why does it complain when setting med3? How do I pass the result of type(of: ...) around to another method to make use of it?

Or simply, how does one get a new instance of AnyClass in Swift 3?

aepryus
  • 4,715
  • 5
  • 28
  • 41
  • 1
    The compiler cannot know that the type stored in `cls3` has an `init()` method. Compare e.g. http://stackoverflow.com/a/32410277/1187415 or http://stackoverflow.com/a/33665262/1187415. – Martin R Oct 21 '16 at 05:08
  • @MartinR Yeah, I had been looking at that comment. It seems casting it to NSObject.Type is allowing me to get what I need, but feels a bit unsatisfying. – aepryus Oct 21 '16 at 05:17
  • You can cast it either to a concrete type or to a protocol type as in the second link, where the protocol demands the init method. – Martin R Oct 21 '16 at 05:19
  • @MartinR I see; ya: [ var med3 = (cls3 as! NSObject.Type).init() ] is working. And in this case, I know all the relevant objects will descend from Domain so casting to Domain.Type works also (with the inclusion of a required init()) – aepryus Oct 21 '16 at 05:28

0 Answers0