Let\'s say I want to split a string by an empty space. This code snippet works fine in Swift 1.x. It does not work in Swift 2 in Xcode 7 Beta 1.
var str = \"
split
is a method in an extension of CollectionType
which, as of Swift 2, String
no longer conforms to. Fortunately there are other ways to split a String
:
Use componentsSeparatedByString
:
"ab cd".componentsSeparatedByString(" ") // ["ab", "cd"]
As pointed out by @dawg, this requires you import Foundation
.
Instead of calling split
on a String
, you could use the characters of the String
. The characters
property returns a String.CharacterView
, which conforms to CollectionType
:
"
let str = "Hello Bob"
let strSplitArray = str.split(separator: " ")
strSplitArray.first! // "Hello"
strSplitArray.last! // "Bob"
let str = "Hello Bob"
let strSplit = str.characters.split(" ")
String(strSplit.first!)
String(strSplit.last!)
In Swift 3 componentsSeparatedByString
and split
is used this way.
let splitArray = "Hello World".components(separatedBy: " ") // ["Hello", "World"]
split
let splitArray = "Hello World".characters.split(separator: " ").map(String.init) // ["Hello", "World"]