arraysstringswift

How can I put each word of a string into an array in Swift?


Is it possible to put each word of a string into an array in Swift?

for instance:

var str = "Hello, Playground!"

to:

var arr = ["Hello","Playground"]

Thank you :)


Solution

  • edit/update:

    Xcode 10.2 • Swift 5 or later

    We can extend StringProtocol using collection split method

    func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Self.SubSequence]
    

    setting omittingEmptySubsequences to true and passing a closure as predicate. We can also take advantage of the new Character property isLetter to split the string.

    extension StringProtocol {
        var words: [SubSequence] {
            return split { !$0.isLetter }
        }
    }
    

    let sentence = "• Hello, Playground!"
    let words = sentence.words // ["Hello", "Playground"]