Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you split a String into a [String] and not [Substring]?

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]?

like image 338
Mark A. Donohoe Avatar asked Mar 10 '18 06:03

Mark A. Donohoe


People also ask

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do you separate data from a string?

Use the string split in Java method against the string that needs to be divided and provide the separator as an argument. In this Java split string by delimiter case, the separator is a comma (,) and the result of the Java split string by comma operation will give you an array split.

How do I split a string without a separator?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


1 Answers

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(){
    }
}
like image 155
Martin R Avatar answered Oct 11 '22 10:10

Martin R