如何在 Swift 中将数组中的所有项目划分为双精度



如果我有

var passengersInDay: [Int] = [3, 3, 3, 3, 3, 2, 2, 1, 1, 1]
var tripCost:Double
var tripDuration:Int
tripCostPerDay = tripCost / Double(tripDuration)

如何将passengersInDay数组的所有元素划分到tripCostPerDay并将结果放入由 Doubles 组成的新数组中?

我尝试使用此操作

var singleDayCosts:[Double] = tripCostPerDay / passengersInDay

但是 swift 一直告诉我,我不能将一个期待 int 的数组划分为 Double?,所以我试图将其称为 Double(passengersInDay)但随后出现了不同的错误。

有什么想法吗?

尝试

let singleDayCosts = passengersInDay.map { tripCostPerDay  / Double($0) }

最新更新