Search code examples
swiftswift4swift-extensions

How do you write an extension to support both [String] and [Substring]?


Normally, to write an extension against a [String], you do this...

extension Array where Element == String {
    ....
}

However, sometimes I don't have a [String] but rather a [Substring]. How can you write an extension that supports either?


Solution

  • Both String and Substring conform to the StringProtocol protocol, so you can define

    extension Array where Element: StringProtocol {
        // ...
    }
    

    Many functions from the standard library have been generalized to take StringProtocol arguments, for example the Int initializer

    convenience init?<S>(_ text: S, radix: Int = default) where S : StringProtocol
    

    so that you can call it with both a String and a Substring:

    let n = Int("1234")
    let m = Int("1234".dropFirst())