ios - How to use protocol extension to provide auto-generated identifier for classes? -


i want provide auto-generated identifier each custom uitableviewcell subclass. try following code, compiler says

type 't' has no member 'autoreuseidentifier'

protocol autoreusable: class {     static var autoreuseidentifier: string { } }  extension autoreusable {     static var autoreuseidentifier: string {         return "\(self)"     } }  extension uitableviewcell: autoreusable {}  func printclassname<t: uitableviewcell>(type type: t.type) {     print(t.autoreuseidentifier) } 

it's okay implement protocol in extension uitableviewcell, prefer implement in protocol extension. how fix this?

the generic t in printclassname(...) not know conforms autoreusable protocol (even if you, developer, knows uitableviewcell so), knows uitableviewcell och uitableviewcell subclass object.

you redeem adding ... t: autoreusable> in generic type constraint of printclassname(...)

func printclassname<t: uitableviewcell t: autoreusable>(type type: t.type) {     print(t.autoreuseidentifier) } 

a more common implementation of printclassname(...) be, however, constraint t protocol autoreusable, rather let printclassname function uitableviewcell objects (subclass objects)

func printclassname<t: autoreusable>(type type: t.type) {     print(t.autoreuseidentifier) } 

this generic function can called type conforming autoreusable, whereas can control default implementation of autoreuseidentifier different extensions protocol autoreusable. e.g., complete example:

protocol autoreusable: class {     static var autoreuseidentifier: string { } }  /* default implementation */ extension autoreusable {     static var autoreuseidentifier: string {         return "\(self)"     } }  /* default implementation uitableviewcell (and subclasses) */ extension autoreusable self: uitableviewcell {     static var autoreuseidentifier: string {         return "\(self) (uitableviewcell)"     } }  /* generic function invokable class type conforming printclassname */ func printclassname<t: autoreusable>(type type: t.type) {     print(t.autoreuseidentifier) }  /* example setup */ extension uitableviewcell: autoreusable { } class foo : autoreusable { } class mycell : uitableviewcell {}  /* example usage */ let foo = foo() let bar = mycell()  printclassname(type: foo.dynamictype) // foo printclassname(type: bar.dynamictype) // mycell (uitableviewcell) 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -