条件绑定的初始化程序必须具有可选类型,而不是Int

时间:2018-10-22 14:51:17

标签: swift

if let hrAverage: Int = (oldHR1+oldHR2+oldHR3+oldHR4+heartRate!)/5 {
    print(hrAverage)
} else {
     let hrAverage = (oldHR1+oldHR2+oldHR3+oldHR4) / 4
     print(hrAverage)
}

收到此错误消息:

  

“用于条件绑定的初始化程序必须具有可选类型,而不是Int”

我一直坚持如何摆脱它。我必须使用可选绑定解开值heartRate

3 个答案:

答案 0 :(得分:1)

不要强行解包您使用条件绑定解包的内容:

if let hr = heartRate {
    let hrAverage: Int = (oldHR1 + oldHR2 + oldHR3 + oldHR4 + hr) / 5
    print(hrAverage)
} else {
    let hrAverage = (oldHR1 + oldHR2 + oldHR3 + oldHR4) / 4
    print(hrAverage)
}

如果在其余的代码中需要hrAverage,则可以使用以下更整洁的方法:

let compactArray = [oldHR1, oldHR2, oldHR3, oldHR4] + [heartRate].compactMap{$0}
let hrAverage: Int = compactArray.reduce(0, +)/compactArray.count

答案 1 :(得分:1)

(oldHR1+oldHR2+oldHR3+oldHR4+heartRate!)/5不会产生使用if let语句所必需的可选内容。

我建议您执行以下操作:

let average = {
    if let rate = heartRate {
        return (oldHR1 + oldHR2 + oldHR3 + oldHR4 + rate) / 5
    } else {
        return (oldHR1 + oldHR2 + oldHR3 + oldHR4) / 4
    }    
}()

现在您有了一个可以在if语句之外使用的变量。如果不需要,可以坚持以下解决方案:

if let rate = heartRate {
    let average = (oldHR1 + oldHR2 + oldHR3 + oldHR4 + rate) / 5
} else {
    let average = (oldHR1 + oldHR2 + oldHR3 + oldHR4) / 4
}

答案 2 :(得分:0)

带编号的变量名称,例如oldHR1oldHR2等,很好地表明您应该使用数组。在这种情况下,我建议您将运行平均值计算提取到其自己的数据类型中,这样可以轻松,轻松地处理这些数据。

struct RunningAverage {
    let maxSize: Int
    var samples: [Double]

    init(maxSize: Int, initialSamples samples: [Double] = []) {
        self.maxSize = maxSize
        self.samples = samples
    }

    mutating func addSample(_ newValue: Double) {
        samples.append(newValue)
        if maxSize < samples.count { samples.removeFirst() }
    }

    /// Will return `nil` when there are no samples.
    /// This allows for easy nil coalescence, without introducing the full burden of
    /// needing to unwrap in the case when the samples are known to be non-empty.
    var average: Double! {
        if self.samples.isEmpty { return nil }
        return samples.reduce(0, +) / Double(samples.count)
    }
}

var runningAverage = RunningAverage(maxSize: 5)
let mockSamples = 1...10
let runningAverages = mockSamples.map { mockSample -> Double in 
    runningAverage.addSample(Double(mockSample))
    return runningAverage.average
}
print(runningAverages) // => [1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]