ios - 如何快速计算 UInt16 值数组的总和?

标签 ios higher-order-functions swift5

如何计算 swift5 中 UInt16 值数组的总和。 下面我分享我的代码,

let myArray: [UInt16] = [23200, 23200, 23300, 23300, 23200, 23300, 23200]
let sumOfArray = myArray.reduce(0, { $0 + $0 })
print("sum of myArray is  \(sumOfArray)")

当我计算数组值的总和时,它给出了一个错误 “执行被中断,原因:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)。”

请帮帮我。

最佳答案

UInt16 是 16 位,因此它可以容纳的最大无符号整数值为 65535。这小于您的结果总和 162700。

使用

let myArray: [UInt16] = [23200, 23200, 23300, 23300, 23200, 23300, 23200]
let sumOfArray = myArray.reduce(0, { (UInt32($0) + UInt32($1)) })
print("sum of myArray is  \(sumOfArray)")

甚至更强大

let sumOfArray = myArray.reduce(0, { $0 + UInt($1)) })

顺便说一句,我相信你有错字,在你的 reduce 中你的意思是 $0 + $1

关于ios - 如何快速计算 UInt16 值数组的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008233/

相关文章:

ios - 如何在 'aspect fit' 模式下将 UIImageView 裁剪为新的 UIImage?

function - react - 组件主体中的功能

c - C 中的高阶函数作为语法糖,工作量最小

Scheme/Lisp CAR 和 CDR 函数的 Python 等效项

ios - 从 'Double' 转换为不相关的类型 'String' 总是失败

cocoapods - 代码 : Failed to render and update auto layout status for UIView: the agent crashed

iphone - ApplicationSignificantTimeChange触发原因

ios - NSURLSession.sharedSession().dataTaskWithRequest(request) 最后执行

ios - 适用于 Mac 上 Windows 的 Cordova 插件添加/删除

SwiftUI 发布的变量未更新