4

Assume I'm writing a social media crawler that handle's multiple accounts (e.g. Facebook, Twitter, etc.)

I define a few protocols for messages (Message has display-name and message body, Timestamped has a timestamp, Forwarded has the original message ID etc).

I then define a protocol for a source of messages, which I've currently written

protocol MessageSource : SequenceType {
    associatedtype MessageType : Timestamped

    func messages (since : NSDate) -> Generator
}

The idea is I can get the n most recent messages by writing msgSource.take(n) and get all messages since a date d by writing msgSource.messages(since : d)

My question is, how do I constrain the Generator.Element inherited from SequenceType to be identical to MessageType, so both generators are guaranteed to return the same type.

Feenaboccles
  • 412
  • 3
  • 12

1 Answers1

1

You can achieve similar functionality by default implementation of protocols:

protocol MessageSource: SequenceType {
    func messages (since : NSDate) -> Generator
}

extension MessageSource where Generator.Element: Timestamped {
    typealias MessageType = Generator.Element

    func foo() -> MessageType? {
        ...
    }
}
JMI
  • 2,530
  • 15
  • 26