map function in Swift converting String to Int? -
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" ] allow numbers = [16, 58, 510] allow strings = numbers.map { (var number) -> string in var output = "" while number > 0 { output = digitnames[number % 10]! + output number /= 10 } homecoming output } // strings inferred of type [string] // value ["onesix", "fiveeight", "fiveonezero"]
i hoping if there explain how code works (it taken apple's developer page swift under "closures). i'm not sure code in "while" loop means :/ how number converted string?
map
function higher order level function , used operation on single elements of array
, homecoming transformed array generated after operations.
numbers.map
traverse each element of array , transform elements doing operation , returned transformed array .
output = digitnames[number % 10]! + output
1) first element in array 16
in first iteration of while loop number % 10
homecoming 6 reminder of 16 after dividing 10
digitname[6]
assign output
six
let strings = numbers.map { (var number) -> string in var output = "" while number > 0 { output = digitnames[number % 10]! + output //16 number /= 10 } homecoming output }
2) divides number
10 , give 1 number 1
3) while number > 0 {
checks if number greater 0 yes 1
4) 1 time again iterate time digitnames[number % 10]!
homecoming one
, appending previous output become one
append output
(which six).so onesix
your first element become onesix
.this done each element , after elements map
homecoming string
array.so string
become
["onesix", "fiveeight", "fiveonezero"]
swift map
Comments
Post a Comment