首页 > 解决方案 > Swift 操作员身份检查

问题描述

操作员身份检查

斯威夫特 4.1,Xcode 9.3

我知道===在 Swift 中使用运算符来检查操作数的身份。我有一种情况,我想检查操作数的身份与运算符的身份 - <strong>我需要检查我的operation参数是否为 +or -


我想做的事

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
    }
    
}

澄清点: 我想知道如何检查operation' 的身份,但 Swift 仅将运算符视为运算符而不是其底层函数。


理想用途

let arr = [1, 2, 3, 4]

let totalSum = arr.total(by: +) //10
let totalProduct = arr.total(by: *) //24

最后的问题

如何检查一个operator(参考其底层功能)的身份?


标签: swiftcollectionsoperatorsidentityswift-extensions

解决方案


推荐阅读