bryanhumps
bryanhumps

Reputation: 43

map function in Swift converting String to Int?

let digitNames = [
    0: "Zero", 1: "One", 2: "Two",   3: "Three", 4: "Four",
    5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]

let strings = numbers.map {
    (var number) -> String in
    var output = ""
    while number > 0 {
        output = digitNames[number % 10]! + output
        number /= 10
    }
    return output
}
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]

I was hoping if there is anyone that could explain how this code works (it is taken from apple's developer page for swift under "closures). I'm not too sure especially what the code in the "while" loop means :/ how exactly is the number converted to string?

Upvotes: 2

Views: 5957

Answers (1)

codester
codester

Reputation: 37189

map function is Higher Order Level function and it is used to do some operation on single elements of array and return a transformed array generated after your operations.

numbers.map will traverse each element of array and transform the elements by doing some operation and returned a transformed array .

output = digitNames[number % 10]! + output  

1) for first element in array 16 in first iteration of while loop number % 10 will return 6 as a reminder of 16 after dividing by 10 so digitName[6] will assign output to Six

let strings = numbers.map {
    (var number) -> String in
    var output = ""
    while number > 0 {
        output = digitNames[number % 10]! + output  //16 
        number /= 10
    }
    return output
}

2) It divides number by 10 and which will give 1 now number will be 1

3) while number > 0 { checks if number is greater than 0 yes it is 1

4) Again iterate now this time digitNames[number % 10]! return One and by appending previous output it will become One append output(which is Six).So OneSix

Your first element become OneSix.This will done for each element and after all elements map return String array.So finally String become

["OneSix", "FiveEight", "FiveOneZero"]

Upvotes: 2

Related Questions