Swift: What is the difference between metatype .Type and .self?

advertisements

What's the difference between metatype .Type and .self in Swift?

Do .self and .Type return a struct?

I understand that .self can be used to check with dynamicType. How do you use .Type?


Here is a quick example:

func foo<T>(type: T.Type) {

    print("\(type)") // or you could do this "\(T.self)" - Swift 2.0 version of print
} 

// now we call that function
foo(Int.self) // this will print Swift.Int

.Type is the actual type you want and .self is to get the type from that specific type and not an instance of it.

.self will not create a new instance, but only return the type (it's a bit confusing if you're here from a different programming language)

func foo2<T>(instance: T) {

    print("\(instance)")
} 

// now we call that function
foo2(42) // this will print 42