Using the split function in Swift 2

Swift2

Swift2 Problem Overview


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 = "Hello Bob"
var foo = split(str) {$0 == " "}

I get the following compiler error:

Cannot invoke 'split' with an argument list of type '(String, (_) -> _)

Anyone know how to call this correctly?

Updated: Added a note that this was for the Xcode 7 beta 1.

Swift2 Solutions


Solution 1 - Swift2

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:

  1. Use componentsSeparatedByString:

    "ab cd".componentsSeparatedByString(" ") // ["ab", "cd"]
    

As pointed out by @dawg, this requires you import Foundation.

  1. 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:

     "😀 🇬🇧".characters.split(" ").map(String.init) // ["😀", "🇬🇧"]
    
  2. Make String conform to CollectionType:

     extension String : CollectionType {}
    
     "w,x,y,z".split(",") // ["w", "x", "y", "z"]
    

Although, since Apple made a decision to remove String's conformance to CollectionType it seems more sensible to stick with options one or two.


In Swift 3, in options 1 and 2 respectively:

  • componentsSeparatedByString(:) has been renamed to components(separatedBy:).
  • split(:) has been renamed to split(separator:).

Solution 2 - Swift2

Swift 4

let str = "Hello Bob"
let strSplitArray = str.split(separator: " ")
strSplitArray.first!    // "Hello"
strSplitArray.last!     // "Bob"
Xcode 7.1.1 with Swift 2.1
let str = "Hello Bob"
let strSplit = str.characters.split(" ")
String(strSplit.first!)
String(strSplit.last!)

Solution 3 - Swift2

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"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMalliochView Question on Stackoverflow
Solution 1 - Swift2ABakerSmithView Answer on Stackoverflow
Solution 2 - Swift2Warif Akhand RishiView Answer on Stackoverflow
Solution 3 - Swift2Nirav DView Answer on Stackoverflow