Created
October 4, 2014 13:45
-
-
Save pyrtsa/c6af49d8f2d95a6b454d to your computer and use it in GitHub Desktop.
Splitting strings by a separator string in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
public func split(separator: String) -> [String] { | |
if separator.isEmpty { | |
return map(self) { String($0) } | |
} | |
if var pre = self.rangeOfString(separator) { | |
var parts = [self.substringToIndex(pre.startIndex)] | |
while let rng = self.rangeOfString(separator, range: pre.endIndex..<endIndex) { | |
parts.append(self.substringWithRange(pre.endIndex..<rng.startIndex)) | |
pre = rng | |
} | |
parts.append(self.substringWithRange(pre.endIndex..<endIndex)) | |
return parts | |
} else { | |
return [self] | |
} | |
} | |
} | |
// Examples: | |
"".split(", ") //=> [""] | |
"a".split(", ") //=> ["a"] | |
"a, b, c, def".split(", ") //=> ["a", "b", "c", "def"] | |
"foobar".split("o") //=> ["f", "", "bar"] | |
"foo".split("foo") //=> ["", ""] | |
// Special case: splitting by empty separator gets the list of glyphs as Strings | |
"".split("") //=> [], notably different from "".split(s) with any other separator s | |
"a".split("") //=> ["a"] | |
"abcd".split("") //=> ["a", "b", "c", "d"] | |
"O\u{305}saka".split("") //=> ["O̅", "s", "a", "k", "a"], works with combining diacriticals |
This seems to cause a runtime error with Swift 1.2 in Xcode 6.3 beta 1 on line 12, but I'm not sure why.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interestingly,
rangeOfString
needsFoundation
imported. TheString
struct is clearly still missing a lot of useful members in the standard library.