Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a first word from a string in Swift?

If we have, for example, situation like this:

 var myString = "Today was a good day"

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

Thanks.

like image 458
Styx1 Avatar asked Sep 23 '16 18:09

Styx1


People also ask

How do I get the first character of a string in Swift?

Use the startIndex property to access the position of the first Character of a String . The endIndex property is the position after the last character in a String . As a result, the endIndex property isn't a valid argument to a string's subscript. If a String is empty, startIndex and endIndex are equal.

How do I get a single character from a string in Swift?

The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters. The variable length of a UTF character in memory makes jumping directly to a character impossible. That means you have to manually loop over the string each time.

How do I get the last character of a string in Swift?

To get the last character of a string, we can use the string. last property in Swift. Similarly, we can also use the suffix() method by passing 1 as an argument to it. The suffix() method can also be used to get the last n characters from a string.


1 Answers

The simplest way I can think of is

Swift 3

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

Swift 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
    }
}

Usage

let string = "hello world"
let firstWord = string.firstWord()
like image 177
wint Avatar answered Sep 20 '22 00:09

wint