我无法确定在Swift中减少自定义托管对象子类数组的语法。我有一个托管对象子类,其属性名为amount,它是一个NSNumber。如何使用reduce函数获取托管对象数组中每个项目的总和。这是我尝试过的,但是我收到一条错误,上面写着“找不到会员'金额'”。
let reduceSum=myArray.reduce(0) {$0 + $1.amount}
我已经查看了这个example,但它没有帮助,因为我找不到成员错误。
答案 0 :(得分:9)
发布此内容之后,我又尝试了一件事并且有效。错误消息具有误导性,让我觉得语法错误,但真正的问题是我需要将NSNumber转换为CGFloat。这是有用的:
let reduceSum=myArray.reduce(0) {$0 + CGFloat($1.amount)}
答案 1 :(得分:3)
extension Array {
var sumInt: Int { return map { $0 as! Int }.reduce(0) { $0 + $1 } }
var sumUInt: UInt { return map { $0 as! UInt }.reduce(0) { $0 + $1 } }
var sumUInt8: UInt8 { return map { $0 as! UInt8 }.reduce(0) { $0 + $1 } }
var sumUInt16: UInt16 { return map { $0 as! UInt16 }.reduce(0) { $0 + $1 } }
var sumUInt32: UInt32 { return map { $0 as! UInt32 }.reduce(0) { $0 + $1 } }
var sumUInt64: UInt64 { return map { $0 as! UInt64 }.reduce(0) { $0 + $1 } }
var sumDouble: Double { return map { $0 as! Double }.reduce(0) { $0 + $1 } }
var sumFloat: Float { return map { $0 as! Float }.reduce(0) { $0 + $1 } }
var sumCGFloat: CGFloat { return map { $0 as! CGFloat }.reduce(0) { $0 + $1 } }
var sum: T {
if !isEmpty {
if first is Int { return sumInt as! T }
if first is UInt { return sumUInt as! T }
if first is UInt8 { return sumUInt8 as! T }
if first is UInt16 { return sumUInt16 as! T }
if first is UInt32 { return sumUInt32 as! T }
if first is UInt64 { return sumUInt64 as! T }
if first is Double { return sumDouble as! T }
if first is Float { return sumFloat as! T }
if first is CGFloat{ return sumCGFloat as! T }
}
return 0 as! T
}
}
用法:
let inputArrayInt:[Int]=[1,2,3]
let sumInt = inputArrayInt.sum // 6
let inputArrayUInt:[UInt]=[1,2,3]
let sumUInt = inputArrayUInt.sum // 6
let inputArrayUInt8:[UInt8]=[1,2,3]
let sumUInt8 = inputArrayUInt8.sum // 6
let inputArrayUInt16:[UInt16]=[1,2,3]
let sumUInt16 = inputArrayUInt16.sum // 6
let inputArrayUInt32:[UInt32]=[1,2,3]
let sumUInt32 = inputArrayUInt32.sum // 6
let inputArrayUInt64:[UInt64]=[1,2,3]
let sumUInt64 = inputArrayUInt64.sum // 6
let inputArrayDouble:[Double]=[1.0,2.0,3.0]
let sumDouble = inputArrayDouble.sum // 6.0
let inputArrayFloat:[Float]=[1.0,2.0,3.0]
let sumFloat = inputArrayFloat.sum // 6.0
let inputArrayCGFloat:[CGFloat]=[1.0,2.0,3.0]
let sumCGFloat = inputArrayCGFloat.sum // 6.0
let inputArray = [1.3,2,3]
let sum = inputArray.sum // 6.3