In this context, neither the .componentsSeparatedByString(" ") method nor the characters.split(" ") method are the “best approach”. Both of these methods will go through the full String object and give the String array as a result. Only after calculating the array we retrieve the first record of this array. If we consider a huge string, in this context this is completely optional, and this will lead to unnecessary overhead.
Instead, for a huge string, use the following method:
let firstDateEntryFast = date.substringToIndex((date.rangeOfString(" ")?.first)!)
This will look for the index of the first occurrence " " and after that return the substring from the beginning of the original string to the first occurrence. Ie, he will never examine or use the original (in this context: the alleged large) line outside the first occurrence point " " .
It should be noted, however, that due to a force reversal (operator (!)), This will crash at runtime if the string does not contain an instance of " " . Therefore, to stay safe and follow the optional Swift convention, use it in the if let clause:
if let myRange = date.rangeOfString(" ") { let firstDateEntryFast = date.substringToIndex(myRange.first!) // at this point, you know myRange is non-empty, and hence, .first can be // force-unwrapped } else { let firstDateEntryFast = date // no " " separation, unexpected? -> action }
As in my first version of the answer, split can be used as an alternative (comparable to componentsSeparatedByString ):
var date = "1,340d 1h 15m 52s" let dateAsArray = date.characters.split(" ").map{ String($0) } let firstDateEntry = dateAsArray[0]
Alternatively, skip storing them in an array and immediately get the first record
var date = "1,340d 1h 15m 52s" let firstDateEntryDirectly = String(date.characters.split(" ")[0])