首页 > 解决方案 > Iterate over functions in Swift

问题描述

I am feeling a bit stupid... I want to get rid of code duplication and so I need to iterate over some functions (a couple of Darwin geometric ones). But when I try

for function in [Darwin.acos, Darwin.cos, Darwin.sin] { print(function(1.0)) }

I get the error "Ambiguous use of 'acos'". I also tried Darwin.acos(Double) and got "Ambiguous reference to member 'acos'" and Darwin.acos { $0 } (and similar) without any luck.

Is it possible to do this? Thank you!

标签: swift

解决方案


除了苏丹所说的:

在 Swift 的未来版本中,这些函数也可用作浮点类型的静态函数,比较SE-0246 Generic Math(s) Functions

let functions = [Double.acos, Double.cos, Double.sin]
for function in functions { print(function(1.0)) }

您现在可以使用来自https://swift.org/download/#snapshots的当前 Swift 开发人员快照尝试此操作。


推荐阅读