Protocol Type Compliance with Related Types

I have a protocol that uses a related type, as such:

protocol Populatable { typealias T func populateWith(object: T) } 

and classes that implement the protocol:

 class DateRowType: Populatable { func populateWith(object: NSDate) { print(object.description) } } class StringRowType : Populatable { func populateWith(object: String) { print(object) } } 

but when I try to execute or check compliance, for example:

 let drt = DateRowType() let srt = StringRowType() let rowTypes = [drt, srt] let data = [NSDate(), "foo"] for (i, p: Populatable) in enumerate(rowTypes) { p.populateWith(data[i]) } 

I get an error message:

The protocol "Populatable" can only be used as a general restriction, since it has its own or related requirements like

What is the correct way to check if an object complies with the Populatable protocol?

Note: all the code needed to verify this question is contained in the question, just copy the blocks of code to the playground.

+6
source share
2 answers

As the error says, you cannot use it for populatable here. I think the correct way is to pass it to EventRowType.

 if let rowController = self.table.rowControllerAtIndex(i) as? EventRowType { 

And you already tested that the EventRowType class conforms to the Populatable protocol. Because if EventRowType does not have a function called "populate", the fast compiler says

The type "EventRowType" does not conform to the "Populatable" protocol

0
source

I don’t think you can use a common path unless this is possible using AnyObject and testing the parameter class in each populateWith function.

But this will work:

 for (i, p) in enumerate(rowTypes) { if let dateRow = p as? DateRowType { dateRow.populateWith(data[i] as! NSDate) } else if let stringRow = p as? StringRowType { stringRow.populateWith(data[i] as! String) } } 

You just need to expand this for each Populatable class you add.

0
source

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


All Articles