Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to split string into an array and trim each value - Swift

Tags:

arrays

csv

swift

In the quest to better understand swift, I'd like to see if there is a more efficient way to write the code below. The code should take the self.categories String, convert it into an array (values separated by commas), and trim each value, before returning the array.

func get_categories() -> Array<String>{
    let categories = self.categories!.componentsSeparatedByString(",")
    var categories_to_return = Array<String>()
    for category in categories {
        categories_to_return.append(category.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()))
    }
    return categories_to_return
}

I've got a suspicion I'm doing something wrong here - perhaps I don't need to create two separate arrays? Perhaps there is another shortcut I've not seen before? Many thanks in advance!

like image 370
Ben Avatar asked May 29 '26 07:05

Ben


2 Answers

You could use map directly on the result of componentsSeparatedByString, like this, and return it without using another variable:

func get_categories() -> Array<String>{
    return self.categories!.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
}

Note: in the map closure, $0 represents the current item from the array of components. It could also be written like this:

func get_categories() -> Array<String>{
    return self.categories!
        .componentsSeparatedByString(",")
        .map { word in word.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
}
like image 53
Eric Aya Avatar answered Jun 01 '26 05:06

Eric Aya


Here is a more generic function for general use cases.

func getSplitAndTrimmed(text: String) -> Array<String> {
    return text.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }
}

The functionality is the same as Eric's wrote.

like image 35
Esqarrouth Avatar answered Jun 01 '26 05:06

Esqarrouth