sabi sabi - 4 months ago 8x
Swift Question

converting String to Character force me to map{$0}, what's the meaning?

Writing a randomStringGenerator() function, I came up with this:

private let characters = ("0123456789" + "abcdefghijklmnopqrstuvwxyz" +

private func generateRandomChar() -> Character {
let index = Int( arc4random_uniform( UInt32( characters.count)))
return characters[index]

func generateRandomString(lenght: Int) -> String {
var string = ""
for _ in 0..<lenght {
return string

please note the second line where I use
, I'm confuse about the use of this (working) syntax. What does it mean to map and do nothing? Is there a more explicative syntax for the same purpose?


someString.characters returns the characters of the string as a String.CharacterView, which is a CollectionType indexed by String.CharacterView.Index.

For the generateRandomChar() function it is more convenient to have an Array which is indexed by Int.

map { $0 } is a shortcut notation for

map { c in 
    return c

i.e. a closure with the "identity transform". This is done here because the map() method applied to any sequence returns an Array:

public func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]

Alternatively you can achieve the same result with

let characters = Array("012 ... XYZ".characters)

Remark: Your generateRandomString() function can be simplified to

func generateRandomString(length: Int) -> String {
    return String((0 ..< length).map { _ in generateRandomChar() })