Programming in Swift: Functions and Types · forEach & map | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5429279-programming-in-swift-functions-and-types/lessons/14

The following code giving error:
let priceLabels = salePrices.map { (price) → String in
String(format: “%.2f”, price)
}

The error is:
error: argument type ‘()’ does not conform to expected type ‘CVarArg’
String(format: “%.2f”, price)

@absarf Does this happen in the original playground too?

could not find the playground for foreach

@vgadkari Please use the Download Materials button to download the playground. Thank you!

for price in prices {
print(price)
}

when we print(price)…how does swift know what “price” means if we never defined it’s meaning? All we did was create an array called “prices” with var prices = [A, B, C, D, E, F, G}?

It’s just a git repository and they crash in xCode whenever I try and run the playgrounds.

Hi! I recommend revisiting the Control Flow part of the Programming in Swift: Fundamentals course if you’re having trouble in this part of the course. (Or watch that course in its entirety, first, if you haven’t already.) Particularly, review the episodes on For Loops and Iterating Collections. I’ve assumed a solid familiarity with for loops in these course.

To answer this specific question, you define “price” in that first line of the for loop with for price in prices. Within the scope of the loop, price refers to one element of the prices array.

let priceLabels = salePrices.map { (price) → String in

String(format: “%.2f”, price)

}

gives error Cannot convert value of type ‘Double’ to expected argument type ‘Int’

Here is a questioned that I don’t think is answered.

This makes total sense to me - it’s a trailing closure on a method call.

let doubled = prices.map() { $0 * 2}

However - why is it OK to remove the parentheses from a method call and use this syntax:

let doubled = prices.map { $0 * 2}

This looks like the syntax for a parameter - not a method.

@sedawk You can use the simplified syntax in this case because the trailing closure is the only argument of map(_:).

Please let me know if you have any more questions or other issues about the whole thing. Thank you!