如何从 Swift 中的字符串返回第一个单词?

问题描述:

例如,如果我们有这样的情况:

If we have, for example, situation like this:

 var myString = "Today was a good day"

返回第一个单词Today"的最佳方式是什么?我认为应该应用映射,但不确定如何应用.

What is the best way to return the first word, which is "Today"? I think mapping should be applied, but not sure how.

谢谢.

我能想到的最简单的方法是

The simplest way I can think of is

let string = "hello world"
let firstWord = string.components(separatedBy: " ").first

斯威夫特 2.2

let string = "hello world"
let firstWord = string.componentsSeparatedByString(" ").first

如果您认为需要在代码中大量使用它,请将其作为扩展

and if you think you need to use it a lot in your code, make it as an extension

extension String {
    func firstWord() -> String? {
        return self.components(separatedBy: " ").first
    }
}

用法

let string = "hello world"
let firstWord = string.firstWord()