Swift String split vs components.
How to split a String into an Array in Swift?
To split a String into an Array using the Swift Standard Library, use the split(separator:) method.
Example split-1:
"Poland,France , Germany,, ".split(separator: ",")
["Poland", "France ", " Germany", " "]Example split-2:
"Poland,France , Germany,, ".split(separator: ",", omittingEmptySubsequences: false)
["Poland", "France ", " Germany", "", " "]Example split-3:
"Poland,France , Germany,, ".split(separator: ",", maxSplits: 1)
["Poland", "France , Germany,, "]Example split-4:
"Poland,France , Germany,, ,.Europe".split(omittingEmptySubsequences: false) { $0.isPunctuation }
["Poland", "France ", " Germany", "", " ", "", "Europe"]
In all cases, the result type is Array<Substring>.
To obtain String values, a transformation is needed:
let s :[Substring] = "Poland,France".split(separator: ",")
let s :[String] = "Poland,France".split(separator: ",").map(String.init)There is also a Foundation’s components(separated:By) method.
Example components-1:
"Poland,France , Germany,,".components(separatedBy: ",")
["Poland", "France ", " Germany", "", ""]Example components-2:
"Poland,France , Germany,, ,.Europe".components(separatedBy: CharacterSet.punctuationCharacters)
["Poland", "France ", " Germany", "", ""]The result type is Array<String>. No transformation is needed to obtain String values.
What is the difference between Swift Standard Library split(separator:) and Foundation’s components(separatedBy:) methods?
There are differences between split and components methods of a Swift’s String. The components method is defined in Foundation and part of NSString and available in files which imported Foundation framework. The split method is part of Swift’s Standard Library. NSString API was evolving from 1990 and was impacted by development of Unicode, that’s why NSString memory storage is UTF-16 encoded and it’s API mainly is working on Unicode code units, in some cases it can be code units. Swift’s String is backed by UTF-8 encoded storage and it’s API is working with cluster code points. If needed the String’s API incudes access to code units via UTF-8, UTF-16 views.
When using components(separatedBy:) NSSting API must use additional operations to interpret Swift’s storage which is encoded in UTF-8 as UTF-16 which is the base for operations of NSString API.
Important to remember is that split can behave as components for adjacent occurences of separator but omittingEmptySubsequences must be set to false.


