【问题标题】:Why can't I use a variable of type float when "reducing" an array?为什么在“减少”数组时不能使用浮点类型的变量?
【发布时间】:2015-02-05 10:27:27
【问题描述】:

我有以下变量:

var calorieTotal: Float {
    return calorieNumberArray.reduce(0) { $0 + $1 }
}

基本上,我正在尝试将我拥有的数组的数字相加。首先,我将变量设置为类型int,但现在我需要它作为float 值。当我尝试这样做时,会出现错误:“'UInt8' 不是 'float' 的子类型”。我怎样才能解决这个问题?请提供新/更改变量的代码,因为我是编程新手。

【问题讨论】:

    标签: swift floating-point int reduce


    【解决方案1】:

    我假设calorieNumberArrayInt 的数组——在这种情况下,只需传递一个浮点数作为初始值,然后将传递给闭包的第二个参数显式转换为Float

    var calorieTotal: Float {
        return calorieNumberArray.reduce(0 as Float) { $0 + Float($1) }
    }
    

    $0 不需要转换,因为它已经是一个浮点数

    【讨论】:

    • 谢谢!这修复了错误。是的,calorieNumberArray 是一个 Int 数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2021-09-26
    • 1970-01-01
    • 2019-06-27
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多