【发布时间】:2016-10-27 00:45:16
【问题描述】:
我有一个数组,例如
[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]
如果之前的值 > 0,我如何更改值为 0 的元素?所以
[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]
变成
[0.0, 0.0, 55.0, 55.0, 55.0, 55.0, 55.0, 22.0, 22.0, 55.0]
我尝试了以下方法,它删除了零,没有别的。
func weightArrayRemovedZero(array: [Double])->[Double]{
var arrayToAlter = [Double]()
for(index,item) in array.enumerated() {
print("The \(item) is at index:\(index)")
if item == 0.0 {
if index > 0 && index < array.count - 1 {
if array[index - 1] != 0.0 {
let nonZeroElement = array[index - 1]
arrayToAlter.append(nonZeroElement)
}
}
} else {
arrayToAlter.append(item)
}
}
return arrayToAlter
}
【问题讨论】: