swift - 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
(参考其底层功能)的身份?
解决方案
推荐阅读
- r - 在 r 中使用排列填充数据集
- c# - HtmlAgilityPack - 如何从 C# 中的 HTML 页面中的特定类中提取数据
- c++ - 使用数组和 rand 计算 1-10 之间整数的实例数?
- arrays - 使用 GraphQL/Apollo Server 时,是否应该因为没有数据库结果而抛出错误?
- c++ - 命名空间“sf”没有成员“时间”
- ruby-on-rails - 如何修复 Rails 6.0.0.beta1 目录已被监视错误?
- android - RecyclerView 适配器是否在配置更改中被破坏?
- kubernetes - 主机和节点之间的 Kubernetes 端口转发?#LoadBalancer
- python - 如何在python中的同一个字符串变量中同时包含单引号和双引号
- ruby - 在独立的 ActiveRecord 应用程序中连接到数据库时出现问题