when I try to create a generic class that implements a UICollectionViewDataSource in swift, it says that my class is not protocol compliant (and once Xcode crashed).
Does this mean that we cannot create a common data provider for the UICollectionView and that we must duplicate the code?
Here is the generic code:
// Enum protocol protocol OptionsEnumProtocol { typealias T static var allValues:[T] {get set} var description: String {get} func iconName() -> String } // enum : list of first available options enum Options: String, OptionsEnumProtocol { typealias T = Options case Color = "Color" case Image = "Image" case Shadow = "Shadow" static var allValues:[Options] = [Color, Image, Shadow] var description: String { return self.rawValue } func iconName() -> String { var returnValue = "" switch(self) { case .Color: returnValue = "color_icon" case .Image: returnValue = "image_icon" case .Shadow: returnValue = "shadow_icon" } return returnValue } } // class to use as the uicollectionview datasource and delegate class OptionsDataProvider<T>: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private let items = T.allValues func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(OptionsCellReuseIdentifier, forIndexPath: indexPath) as! GenericIconLabelCell let item = self.items[indexPath.row] // Configure the cell cell.iconFileName = item.iconName() cell.labelView.text = item.description return cell } }
But since this failed, I have to use this non-general form:
enum Options: String { case Color = "Color" case Image = "Image" case Shadow = "Shadow" static var allValues:[Options] = [Color, Image, Shadow] var description: String { return self.rawValue } func iconName() -> String { var returnValue = "" switch(self) { case .Color: returnValue = "color_icon" case .Image: returnValue = "image_icon" case .Shadow: returnValue = "shadow_icon" } return returnValue } } class OptionsDataProvider: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private let items = Options.allValues func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(OptionsCellReuseIdentifier, forIndexPath: indexPath) as! GenericIconLabelCell let item = self.items[indexPath.row]
which oblige me to duplicate the class for each type of enumeration that I have.
Exact error:

generics ios xcode swift uicollectionview
Dragouf
source share