[swift-evolution] [Draft] Rename Sequence.elementsEqual

Gwendal Roué gwendal.roue at gmail.com
Tue Oct 17 02:03:50 CDT 2017

>> Modeling is, by definition, imperfect. The question is, what imperfect model is most useful _to Swift_. The idea is that conforming Set and Dictionary to Collection is on balance more useful than not doing so; that having two protocols, Sequence and Collection, is on balance more useful than having one or three, and that the set of semantic guarantees of Collection are on balance more useful than other possible sets of semantic guarantees.
> That is your idea which is disputed and underlined with arguments whereas you keep repeating that Set behaves as dictated by its conformance without giving use cases why this should be useful.


You can't *control* the ordering of a set or a dictionary, but you can still *rely* on it.

For example, to find a key in a dictionary that is associated a given value, you can rely on the fact that a dictionary's order is guaranteed to be stable, and that on top of that its indexes can address the dictionary itself, but also its keys and values sequences. The code below has no bug;

let dict = ["a": "foo", "b": "bar", "c": "needle"]

// Find a key associated with "needle"
if let index = dict.values.index(of: "needle") {
    let key = dict.keys[index]
    print(key) // prints "c"

It's more difficult to find a use case for set's ordering and indexes. But since you ask, here is an example. The goal is to find any element which is not equal to another value, in any collection:

extension Collection where Element: Equatable {
    /// Returns any element which is not equal to the given element
    func anyElement(notEqualTo v: Element) -> Element? {
        if let i = index(of: v) {
            if let alt = index(i, offsetBy: 1, limitedBy: endIndex), alt != endIndex {
                return self[alt]
            if i == startIndex {
                return nil
            return first
        return first

Set([1, 2, 3]).anyElement(notEqualTo: 1) // 2 or 3
Set([1, 2]).anyElement(notEqualTo: 1)    // 2
Set([1]).anyElement(notEqualTo: 1)       // nil
Set([2]).anyElement(notEqualTo: 1)       // 2
Set([]).anyElement(notEqualTo: 1)        // nil

That *can* be useful, isn't it?

Gwendal Roué

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171017/cfae49a3/attachment.html>

More information about the swift-evolution mailing list