Confused about implementing SequenceType

7 views
Skip to first unread message

Jens Alfke

unread,
Jun 1, 2015, 9:53:57 PM6/1/15
to swift-l...@googlegroups.com
I defined a struct type that represents a set of Peer objects. (Using Set<Peer> would not be appropriate for reasons I’ll skip.) The internal implementation is a Dictionary mapping UUID strings to Peers. I want the set to be usable in a for…in… loop so I need to implement SequenceType. It’s straightforward except for the definition of the Generator typealias:

public struct PeerSet : SequenceType {
    private var byUUID = [String:Peer]()
    // ...
    public typealias Generator = ?????  // What goes here??
    public func generate() -> Generator {
        return byUUID.values.generate()
    }
}

OK, Generator has to be defined as “the same type that Dictionary.values.generate() returns”. But what exactly that type is, is not easy to work out; even armed with swiftdoc.org I was getting confused. Finally I solved the problem by replacing “?????” with “Int” and looking at the resulting error message:

PeerSet.swift:46:30: error: 'MapSequenceGenerator<DictionaryGenerator<String, Peer>, Peer>' is not convertible to 'Generator'
        return byUUID.values.generate()
               ~~~~~~~~~~~~~~^~~~~~~~~~

OK, so the actual type is MapSequenceGenerator<DictionaryGenerator<StringPeer>, Peer>. I replaced Int with that mouthful, and it works.

This seems a bit unintuitive and awkward, especially since the compiler already knows what the type should be (since it know how to name it in the error message.) Is there a clearer way to write this that isn’t as weird?

—Jens
Reply all
Reply to author
Forward
0 new messages