一尘不染

如何在Swift中将字符串的每个单词放入数组?

swift

是否可以在Swift中将字符串的每个单词放入数组中?

例如:

var str = "Hello, Playground!"

至:

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

谢谢 :)


阅读 273

收藏
2020-07-07

共1个答案

一尘不染

编辑/更新:

Xcode 10.2•Swift 5或更高版本

我们可以StringProtocol使用集合拆分方法进行扩展

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

设置omittingEmptySubsequences为true并通过闭包作为谓词。我们还可以利用new
Character属性isLetter来分割字符串。

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

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