Anton Anton - 5 months ago 21
Swift Question

struct arguments - array

Here's a simple code:

struct Car {
var model: String
var producer: String
var year: Int
}

func AverageYear(years : [Int]) -> Int {
var x : Int = 0
for i in 0..<years.count {
x += years[i]
}
return x / years.count
}

var list = [Car(model: "C400", producer: "Mercedes-benz", year: 2014),
Car(model: "GLE450", producer: "Mercedes-benz", year: 2016)]

print(AverageYear([list[0].year, list[1].year]))


How can I replace
AverageYear([list[0].year, list[1].year])
- without enumerating all the elements? Something like
AverageYear([list.year])

Answer

You can use map to construct years array from the given array of cars like that:

var list = [Car(model: "C400", producer: "Mercedes-benz", year: 2014),
            Car(model: "GLE450", producer: "Mercedes-benz", year: 2016)]

let years = list.map { $0.year }
print(AverageYear(years))