I\'m trying to make an iOS app in Swift that requires me to split a line of text at the first colon (:) of a line. I\'ve tried using the the componentsSeparatedByString meth
Swift 4.2, Swift 5 answer:
let str = "Hello, this is, a, playground"
let splitStringArray = str.split(separator: ",", maxSplits: 1).map(String.init)
print(splitStringArray) // ["Hello", " this is, a, playground"]
the first
It's just a typo, not componentSeparatedByString
, but componentsSeparatedByString
let stringArray = contents.componentsSeparatedByString("\n")
// ^
the second
You can use builtin split
function which can specify maxSplit
:
let str:NSString = "test:foo:bar"
let result = split(str as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
// -> ["test", "foo:bar"]
Note that the type of the result is [String]
. If you want [NSString]
, just cast it:
let result:[NSString] = split(string as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
// ^^^^^^^^^^^
Swift 2 answer with split function(for Swift 3 use maxSplitS parameter, just add "s"):
let fullString = "A B C"
let splittedStringsArray = fullString.characters.split(" ", maxSplit: 1).map(String.init)
print(splittedStringsArray) // ["A","B C"]