How to convert the String into an array in swift example | Xcode example
Sometimes, We want a string to be split into substring and converted into an array.
The string can be split based on a delimiter such as space or comma.
How to convert String into an array in swift
- use String components with the separatedBy attribute. String components method that takes separatedBy attribute, converted to an array. It works in the Swift 3 version only.
import Foundation
let str : String = "first middle last";
let strArray = str.components(separatedBy: [" "])
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>
using String split with separator
The string contains a split with separator value, convert into an array. split is a function introduced in the Swift 4 version
let str : String = "first middle last";
let strArray = str.split(separator: " ")
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>
Output:
["first", "middle", "last"]
Array<Substring>
Another way using the whereSeparator in the split function
import Foundation
let str : String = "first middle last";
let strArray = str.split(whereSeparator: {$0 == " "})
print(strArray) // ["first", "middle", "last"]
print(type(of: strArray)) // Array<Substring>