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!
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()) }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With