Swift: Constrained Extensions

Here’s a simple example that extends arrays comprised of Comparable elements.

If you saw my earlier post/tweet apologies. Swift still doesn’t support type-requirements because they make generic parameters become non-generic. I need more sleep.

 

2 Comments

  • I’m trying to make a constrained extension on Dictionary, but I can’t seem to get it right. If you have time, could you check out this gist and tell me what I’m doing wrong? Thanks, and keep up the fantastic blogging!

    https://gist.github.com/JoshuaSullivan/cd2561993201069ab7bf

  • The problem with this is autocomplete shows all methods

    extension Array where Element:Comparable {
    var maxIndex : Int? {
    // Thanks Mike Ash, Jacob Bandes-Storch, Bas Broek
    return self.enumerate().maxElement({$1.element > $0.element})?.index
    }
    }

    struct Person {

    }

    let a = [1, 2, 3, 4]
    let b = [Person(), Person()].maxIndex // Here maxIndex is autocompleted

    and an error message that is vague

    > Type of expression is ambiguous without more context