Fast Generators and Protocol Extensions

I have a Reusable protocol that has a static function static func reuseId() -> String and a protocol extension that defines the default implementation for this function. Then I implemented an extension on UITableViewCell to comply with the Reusable protocol. Now I can use the function on my TableViewCells without any problems: SomeTableViewCell.reuseId() .

I have a problem with Generics. I have a generic class that has a generic parameter of type UITableViewCell :

 internal class SomeClass<CellType: UITableViewCell>: NSObject { ... } 

I want to use the function specified in Reusable in my generic class on CellType , but unfortunately this does not work properly. The compiler always generates a Type 'CellType' has no member 'reuseId' .

Does anyone know why this is happening? Is there a workaround?

I am using Xcode 7.0 with Swift 2.0.

Greetings from Germany

UPDATE: Here is an example code that better shows my problem:

 import UIKit protocol Reusable { static func reuseId() -> String } extension Reusable { static func reuseId() -> String { return String(self).componentsSeparatedByString(".").last! } } extension UITableViewCell: Reusable { } class SomeGenericClass<CellType: UITableViewCell> { func someFunction() { let reuseIdentifier = CellType.reuseId() } } 

This code generates the above error, but I do not quite understand why this is happening. I think the main difference from the sample code that jtbandes is hosted in is using a static function.


UPDATE: The problem is fixed in Xcode 8.3 beta 2. The sample code above now works as expected (after moving it to Swift 3, of course).

0
source share
2 answers

This is an interesting problem. Your code seems to work; You may want to create a file with the extension .

Here is a workaround that works correctly:

 class SomeGenericClass<CellType: Cell> { func someFunction() { let reuseIdentifier = (CellType.self as Reusable.Type).reuseId() } } 
0
source

Another way (workaround) to get what you need:

 class GenericExample<CellType:UITableViewCell where CellType:Reusable> { func test() -> String { return CellType.reuseId() } } GenericExample<UITableViewCell>().test() // returns "UITableViewCell" GenericExample<MyCell>().test() // returns "MyCell" 
0
source

Source: https://habr.com/ru/post/1236519/


All Articles