1

I'm a bit confused about what happens when we write something like UIView.type. What is type?

Consider the following:

struct myClass {
    var viewType : UIView.Type
    var justView: UIView
}

The first returns to us UIView.Type, and the second is just UIView.

What is the difference? UIView is class, so we can treat that variable like any UIView. What is the point of using UIView.type?

plamut
  • 3,085
  • 10
  • 29
  • 40
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • 1
    https://medium.com/ios-os-x-development/types-and-meta-types-in-swift-9cd59ba92295 – Alexander Feb 02 '18 at 16:19
  • Metatypes can be tricky. I think you could best learn about them and see them in action in Smalltalk or Objective C – Alexander Feb 02 '18 at 16:21
  • @Alexander why should i study them in Obj-C when i use Swift? – Evgeniy Kleban Feb 02 '18 at 16:21
  • Essentially, initializes and `class` and `static` functions/properties of a type `T` don't belong to an instance of type `T` (like instance functions and properties do), but rather, they can be thought of as members of the metatype, `T.Type`. – Alexander Feb 02 '18 at 16:22
  • Because you don't see them as much in Swift. E.g. when you do `[[NSArray alloc] init]`, you're sending the `alloc` message to `NSArray`. But `NSArray` isn't an object, it's a class, how can it receive messages? Well actually, `NSArray` is an instance of a metaclass. Class methods like `alloc` are actually instance members of `NSArray`'s metaclass – Alexander Feb 02 '18 at 16:25
  • The usefulness of this is that it unifies the message mechanics of instance and class methods, because both instance and class methods can be thought of as just instance methods. Instance methods are members of the type, whereas class methods are instance members of the metatype. – Alexander Feb 02 '18 at 16:26
  • I think the best way to master this would be to poke in a smalltalk environment a bit. – Alexander Feb 02 '18 at 16:27
  • @Alexander to simplify what u saying, you mean that alloc is sending for class.type, and init to class itself? – Evgeniy Kleban Feb 02 '18 at 16:27
  • Yes. `alloc` is a message sent to `NSArray` (which is an instance of the `NSArray` metatype, spelt `NSArray.Type` in Swift). It returns a newly allocated instance (object) of `NSArray`, to which `init` is sent. – Alexander Feb 02 '18 at 16:31
  • @Alexander thanks for your help now it become clearer for me :) – Evgeniy Kleban Feb 02 '18 at 16:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164417/discussion-between-alexander-and-evgeniy-kleban). – Alexander Feb 02 '18 at 16:32

0 Answers0