dimanche 23 octobre 2016

How do I pass around the result of type(of: ...) in Swift 3?

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?





Aucun commentaire:

Enregistrer un commentaire