iosswiftintrospectionmetatype

Swift Metatyping Inconsistency


Given the following code...

protocol MyProtocol {}
enum MyEnum: MyProtocol {}
struct MyStruct: MyProtocol {}
class MyClass: MyProtocol {}
func MyFunction(parameter: MyProtocol.Type) -> String {
    return "Hi"
}

Why do i have to use .self when assigning a variable...

var variable: MyProtocol.Type = MyStruct.self

and not when I am passing a metatype as a function parameter?

var result = MyFunction(MyStruct)

Solution

  • It looks like either a compiler bug. Personally I feel like .self should be included in the function argument.

    However, once Swift's source code is released later this year there might be a better explanation. In the mean time you could file a radar.

    EDIT: It appears to drop the .self requirement if the Class.Type is the only function parameter. Swift leave out .self to invoke a function which needs metatype?