1

How to write a function that allow any objects but must be Printable and Equatable array of objects in Swift?

class func withItems(items: [AnyObject]){

}
  1. I need items to be Printable and Equatable
  2. I need to declare that items array as attribute of my class

Thanks

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162

1 Answers1

4

You can use generic constraints to require both protocols in a function:

class func withItems<T: AnyObject where T: Equatable, T: Printable>(items: [T]) {
    // ...
}

Requiring that of a stored property is trickier, since Equatable can't be used as a type. In order to do so you'd essentially need to make the class itself generic. You'd probably be better off declaring items as an array of AnyObject and providing access to it through generic methods like this one.

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • But I get `T is not identical to AnyObject` if I have an stored property of type `[AnyObject]` – Daniel Gomez Rico Dec 05 '14 at 16:02
  • 1
    AnyObject is just another protocol - can you try ``? – Nate Cook Dec 05 '14 at 16:12
  • There's a problem when I try to get description from the object. The items array is: `var items: [AnyObject] ` and if I try items[indexPath.row].description it prints the Object default description, not the override one. If I do a manual cast to the object type it prints right, but if I left it as AnyObject it prints the default, why? – Daniel Gomez Rico Dec 05 '14 at 18:33
  • I "solve it" creating another array with the descriptions inside the method like this: `controller.titles = items.map( { $0.description } )` – Daniel Gomez Rico Dec 09 '14 at 14:17