将变量设置为运算符函数 [英] Setting a variable to an operator function

查看:46
本文介绍了将变量设置为运算符函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数是 Swift 中的一等公民,我可以这样做:

Being functions are first class citizens in Swift, I can do this:

func someFunc(arg: Int) -> Int { return 1}
let v = someFunc
let out = v(3)

这按预期工作.但同样的事情不能应用于似乎有点奇怪的运算符,因为运算符实际上只是函数.

And this works as expected. But the same thing can't be applied to operators which seems a little strange, because operators are really just functions.

func +(lhs: Int, rhs: Int) -> Int { return 1}
let op = + // results in an error

是否有实际的方法来完成将运算符分配给变量?或者是将运算符包装在另一个可以分配的函数中的唯一方法?

Is there an actual way to accomplish assigning an operator to a variable? Or is the only way to wrap the operators in another function which can then be assigned?

推荐答案

用括号将运算符括起来,并明确指定类型,允许它进行解析和类型检查:

Surrounding the operator with parentheses, and specifying the type explicitly, allows it to parse and typecheck:

let op: (Int, Int) -> Int = (+)

这篇关于将变量设置为运算符函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆