这是一个简单的代码:
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]))
如何在不枚举所有元素的情况下替换AverageYear([list[0].year, list[1].year])
?像AverageYear([list.year])
答案 0 :(得分:0)
你可以使用 map 从给定的汽车数组构建年数组:
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))
答案 1 :(得分:-1)
Reduce让它在单行中运行:
struct Car {
var model: String
var producer: String
var year: Int
}
var list = [Car(model: "C400", producer: "Mercedes-benz", year: 2014),
Car(model: "GLE450", producer: "Mercedes-benz", year: 2016)]
// slice the array to get the elements you want
let slice = list[0...1]
// sum every car.year in the slice and divide by the count
let averageYear: Int = slice.reduce(0){ $0 + $1.year } / slice.count
print(averageYear) // -> 2015
请注意,我使用了list[0...1]
,这意味着“元素0到1,包括”。它返回原始数组的切片。如果我有10个元素,我可以list[5...8]
,它会给我一个包含元素5,6,7,8的数组切片。