13

Consider the following extension:

extension Array where Element == String {
    func foo(){
    }
}

And consider the following string that I want to split so I can use the extension...

let string = "This|is|a|test"
let words = string.split(separator: "|")

The problem is words is a [Substring] and not [String] so I can't call foo() on it.

So in Swift 4, how do I split a string to return a [String] and not a [Substring]?

6
  • string.components(separatedBy: .whitespaces) will return an array of strings Commented Mar 10, 2018 at 6:43
  • 2
    If you really need to use split method you can map them into strings .map(String.init) Commented Mar 10, 2018 at 6:45
  • string.components(separatedBy: ."|") Commented Mar 10, 2018 at 6:46
  • Ideally you'd modify the extension to work with substrings, I presume Commented Mar 10, 2018 at 6:46
  • @JohnDvorak, I had just posted a second question specifically asking how to write an extension that works with both. Can you elaborate in an answer? Commented Mar 10, 2018 at 6:47

1 Answer 1

14

As Leo said above, you can use components(separatedBy:)

let string = "This|is|a|test"
let words = string.components(separatedBy: "|")
words.foo()

instead, that returns a [String].

If you want to stick with split() (e.g. because it has more options, such as to omit empty subsequences), then you'll have to create a new array by converting each Substring to a String:

let string = "This|is|a|test"
let words = string.split(separator: "|").map(String.init)
words.foo()

Alternatively – if possible – make the array extension method more general to take arguments conforming to the StringProtocol protocol, that covers both String and Substring:

extension Array where Element: StringProtocol {
    func foo(){
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly. And your StringProtocol solution actually answers my other question that I just posted. Feel free to copy it there and I'll accept that there as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.