我知道在Swift中使用===
运算符来检查操作数的身份。我有一种情况,我想检查我的操作数的身份与操作员的身份 - 我需要检查我的operation
参数是 +
还是{ {1}}。
-
澄清点: 我想知道如何检查extension Collection where Element: Numeric {
func total(by operation: (Element, Element) -> Element) -> Element {
return (operation === + || operation === -) ? reduce(0, operation) : reduce(1, operation)
// For '+', '-', you need to use reduce with the initial value of 0
// For '*', '/', you need to use reduce with the initial value of 1
}
}
的身份,但Swift只将运营商视为运营商而非其基础功能。
operation
如何查看let arr = [1, 2, 3, 4]
let totalSum = arr.total(by: +) //10
let totalProduct = arr.total(by: *) //24
的身份(请参阅其基础功能)?