Linked Questions

Popular Questions

Swift extension for [String]?

Asked by At

I'm trying to write an extension method for [String].

It seems you can't extend [String] directly ("Type 'Element' constrained to non-protocol type 'String'"), though I came across this trick:

protocol StringType { }
extension String: StringType { }

But I still can't quite make the Swift type system happy with this:

extension Array where Element: StringType {
    // ["a","b","c","d","e"] -> "a, b, c, d, or e".
    func joinWithCommas() -> String {
        switch count {
        case 0, 1, 2:
            return joinWithSeparator(" or ")
        default:
            return dropLast(1).joinWithSeparator(", ") + ", or " + last!
        }
    }
}

The joinWithSeparator calls are "Ambiguous". I've tried everything I could think of, like using (self as! [String]) (and a bunch of similar variants), but nothing seems to work.

How can I make the Swift compiler happy with this?

Related Questions