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

Thorsten Seitz tseitz42 at icloud.com
Tue Oct 17 10:51:23 CDT 2017

Hi Gwendal, these are use cases for using indices as unordered references which certainly are useful. I was looking for use cases depending on the order exposed by Sequence, specifically use cases for elementsEqual.


> Am 17.10.2017 um 09:03 schrieb Gwendal Roué <gwendal.roue at gmail.com>:
>>> 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.
> Hello,
> 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/be6ee317/attachment.html>

More information about the swift-evolution mailing list