Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift version of componentsSeparatedByString

Tags:

ios

swift

I know its noob question, i really search around before ask. But there is not exact answer of what i want to know. How we split string into the array without using Objective C? For example:

var str = "Today is so hot" var arr = str.componentsSeparatedByString(" ")  // * 
  • I know it doesnt work but i am looking for like that. I want to split string with " " (or another char/string)

Idea:It might be very good for me, making extension of string class. But i dont know how i do that.

Edit: Forgetting import Foundation. If I import foundation it will work. But is there any way to do with extending String class? Thank you

like image 539
Antiokhos Avatar asked Aug 10 '14 08:08

Antiokhos


People also ask

How do you split a string in Swift?

Swift – Split a String by Character Separator To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.

How do you split a string in Objective C?

Objective-C Language NSString Splitting If you need to split on a set of several different delimiters, use -[NSString componentsSeparatedByCharactersInSet:] . If you need to break a string into its individual characters, loop over the length of the string and convert each character into a new string.


1 Answers

If you want to split a string by a given character then you can use the built-in split() method, without needing Foundation:

let str = "Today is so hot" let arr = split(str, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false) println(arr) // [Today, is, so, hot] 

Update for Swift 1.2: The order of the parameters changed with Swift 1.2 (Xcode 6.3), compare split now complains about missing "isSeparator":

let str = "Today is so hot" let arr = split(str, maxSplit: Int.max, allowEmptySlices: false, isSeparator: { $0 == " "} ) println(arr) // [Today, is, so, hot] 

Update for Swift 2: See Stuart's answer.

Update for Swift 3:

let str = "Today is so hot" let arr = str.characters.split(separator: " ").map(String.init) print(arr) 
like image 117
Martin R Avatar answered Sep 27 '22 19:09

Martin R