split the string

Hi,
Id like to split the string = "aabbccddee". .split function requires you to use some sort of separator. Any suggestion how to make it?

The main task is actually to count how many times the letters appear in a string. I believe the solution may be related to .map.

Any help appreciated.
In Swift a String is collection of Characters, so you can do things like this:

Code Block
for ch in "aabbccddee" {
print(ch)
}


IMPORTANT In Swift a Character is not a simple ASCII character but rather an extended grapheme cluster. See the docs for more.

This means you can apply collection methods on those characters. For example, you can use filter(_:) like so:

Code Block
"aabbccddee".filter { $0 == "a" }


One common idiom is to chain these methods together, like this:

Code Block
"aabbccddee"
.filter { $0 == "a" }
.count


The main task is actually to count how many times the letters appear
in a string.

My weapon of choice for that is Dictionary.init(_:uniquingKeysWith:).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
I once wrote an extension to do this:

Code Block
extension Sequence where Element: Hashable { //extension on sequence where element conforms to hashable protocol
var frequencies: [Element: Int] { //dictionary of key element and value int
return Dictionary(self.map{ ($0, 1)}, uniquingKeysWith: { $0 + $1} ) //creates new dictionary for key-value pairs in sequence and increments the value for duplicate keys
}
}
extension String {
var frequencies: [Character: Int] {
return Array(self).frequencies
}
}
"aabbccddee".frequencies

yields (dictionary is not ordered)

["e": 2, "a": 2, "b": 2, "c": 2, "d": 2]

Or
"hello you".frequencies
["h": 1, " ": 1, "e": 1, "l": 2, "o": 2, "u": 1, "y": 1]
To further detail how frequencies is built, the expanded version of
Code Block
 return Dictionary(self.map{ ($0, 1)}, uniquingKeysWith: { $0 + $1} ) 

would be

Code Block
let partiel = Array("aabbccddee").map{ ($0, 1)} // split String into an Array of pairs with the char and 1 as value
// partiel = [("a", 1), ("a", 1), ("b", 1), ("b", 1), ("c", 1), ("c", 1), ("d", 1), ("d", 1), ("e", 1), ("e", 1)]
// Then build a Dict from this Array ; as each key must be unique, we define how to combine when we find an already used key: add the nextValue to the existing one
let counted = Dictionary(partiel, uniquingKeysWith: { (prevCountForKey, nextValue) in prevCountForKey + nextValue} ) // nextValue is 1 here
// counted = "c": 2, "b": 2, "a": 2, "d": 2, "e": 2]
// Closure can then simply be written { $0 + $1}


split the string
 
 
Q