Split string with separator of another string

How can I split string with separator of another string or multiple characters?

let s = "#! it #! happens #! sometimes"
s.split(separator: "#!")

Thanks

There's a method in Foundation that does what you want

import Foundation

let s = "#! it #! happens #! sometimes"
print(s.components(separatedBy: "#!")) // ["", " it ", " happens ", " sometimes"]
2 Likes

Thanks.
Now, I can find it under StringProtocol

The split method comes from the Swift Standard Library and is the modern, native way to split Unicode strings.

components(separatedBy:) comes from Foundation, belongs to the older NSString API, and is inherited through bridging.

Prefer using Standard Library String methods and fall back to NSString methods only when the required functionality is missing.

When you import Foundation, autocompletion presents a mix of String and NSString methods, because String is a toll-free bridge to NSString. At that point, it becomes unclear which method belongs to which type, and the only safe option is to jump to the documentation.

Importing SwiftUI or UIKit implicitly imports Foundation.

String.split(separator:omittingEmptySubsequences:) defaults to omittingEmptySubsequences = true, which leads to different results than NSString.components(separatedBy:).

If you set omittingEmptySubsequences to false, the result matches components(separatedBy:).

3 Likes

Thank you for pointing that difference out!

IMHO having omittingEmptySubsequences = true by default is quite unfortunate and dangerous (for example it prevents a proper rountrip of a == a.split.join) but maybe I'm too picky.

2 Likes

Hmm, I find your point interesting.

Especially when developing a new Standard Library logic. I would say that a study of the behavior of other languages, especially those supported by Swift, such as C, C++, and Objective-C, could be a good place to check the behavior of similar methods. After that, I would look at the standard libraries of other languages.

String is a toll-free bridge

String is likely bridged rather than toll-free bridged with NSString, due to differences in memory encoding.