How to avoid using A.self?

Take this code:

protocol P: class { static var hello: String { get } } class A: P { class var hello: String { return "Hello" } } class B: A { override static var hello: String { return "Hello World" } } class C: A {} class D: C { override static var hello: String { return "Hello D" } } func sayHello(elements: P.Type...) { for p in elements { print(p.hello) } } func sayHelloAgain(elements: A.Type...) { for p in elements { print(p.hello) } } func sayHelloThe3rd(elements: [A.Type]) { for p in elements { print(p.hello) } } sayHello(A.self, B.self, C.self) sayHelloAgain(A.self, B.self, C.self) 

Compare this to this (taken from this presentation )

 func register<T: UITableViewCell where T: ReusableView, T: NibLoadableView>(_: T.Type) { ... } tableView.register(FoodTableViewCell) 

Why should I use A. in one case, but not in another? And also, you do not need to use .self when calling with one argument.

 sayHello(A) sayHello(A, B) //doesn't compile 
+4
swift
source share
1 answer

.self is a syntax salt. This is not necessary from a technical point of view, but it exists to cause errors in the code, which is often the result of a typo, for example:

 struct Foo { } let foo = Foo 

This code will give you a compiler error telling you that either you need to make an initialization / function / method call, or add .self if you want to refer to the type.

In the last example, the context refers exclusively to types, not values, so there is no way to knock them from another, so .self not required.

There may be a way to change the function declaration in your example so as not to require .self , but I don't know about such a function. I would be interested to know.

+2
source share

All Articles