如何编写Swift中缀函数?

时间:2016-01-26 15:04:27

标签: swift infix-notation

我已经看到了这一切,但我无法绕过它。不知何故,似乎神奇地,一些中缀函数工作正常,但其他函数根本无法编译。例如:

A function named "*" works fine, but one named "then" does not.

正如您在此处看到的那样,我的then函数作为传统函数工作,但不是作为中缀函数,但我的*函数却存在相反的问题。 then函数成为中缀函数的神奇之处是什么?

附带问题:为什么我的*功能不能作为传统功能工作?

纯文本阅读器和复制粘贴的代码:

public func * (let left:String, let right:Int) -> String {
    if right <= 0 {
        return ""
    }

    var result = left
    for _ in 1..<right {
        result += left
    }

    return result
}
*("Left", 6) // error: '*' is not a prefix unary operator
"Left" * 6   // "LeftLeftLeftLeftLeftLeft"

public func then (let left:String, let _ right:String) -> String {
    return left + right
}
then("Left", "Right") // "LeftRight"
"Left" then "Right"   // 2 errors: Consecutive statements on a line must be separated by ';'

2 个答案:

答案 0 :(得分:6)

Swift标准库已将var options = { url: url, followRedirect: false, headers: { "Authorization": auth } }; 定义为中缀运算符:

*

您可以在中找到预定义运算符的列表 Swift Standard Library Operators Reference。或者,在Xcode中的infix operator * { associativity left precedence 150 } 语句上“命令单击”并搜索“operator”。

要在“传统”函数调用中使用运算符,必​​须将其括在括号中:

import Swift

如果要定义自己的中缀运算符,则必须添加 (*)("Left", 6) 声明。但请注意,这只是一组受限制的 字符对运算符有效(有关精确规则,请参阅Language Reference->Lexical Structure->Operators)。特别是运营商 name必须(正如@dfri已经说过的那样)开头 /,=, - ,+,!,*,%,&lt;,&gt;,&amp;,|,^,?,〜或其他一些“符号”字符。特别是,“then”不是有效的运营商名称。

答案 1 :(得分:2)

本地,

*已经定义为Swift中的二进制中缀运算符:

infix operator * {
    associativity left
    precedence 150
}

因此,func * (...形式的任何函数都将重载此二进制中缀运算符。另一方面,如果您尝试将*运算符用作前缀一元运算符,则会出现*不是前缀的描述性错误一元运算符“,因为*本身不存在作为前缀运算符。

您当然可以定义自己的前缀运算符*

prefix operator * { }
prefix func * (rhs: Int) -> Int {
    return rhs*rhs
}

var a : Int = 2
var b : Int = *a // 4

要包装它:一些运算符本身存在于Swift中作为前缀和中缀运算符,例如: -

/* Declared natively in Swift */
infix operator - {
    associativity left
    precedence 140
}

prefix operator - {
}

/* Example usage */
let a : Int = 2 - 1 // 1,  '-' infix operator used
let b : Int = -1    // -1, '-' prefix operator used

而其他人,例如*,只是(本机地)用作中缀运算符。

另请注意,如果要定义自己的自定义中缀运算符,其允许的名称将受到如下约束:

  

自定义运算符可以以ASCII字符之一/,=, - 开头,   +,!,*,%,&lt;,&gt;,&amp;,|,^,?或〜,或下面语法中定义的Unicode字符之一(包括来自   数学运算符,杂项符号和标志Unicode   块等等。在第一个字符之后,组合Unicode   也允许使用字符。

来自Language Reference - Lexical Structure

相关问题