Using the split function in Swift 2

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.

  2. 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) // ["😀", "🇬🇧"]
    
  3. 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:).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)