我怎么定义!!作为自定义后缀运算符?
How can I define !! as a custom postfix operator?
我正在尝试创建自己的自定义运算符!!
postfix operator !! //error
static postfix func !! (optionalValue: Optional<T>) -> T {
// realisation
}
我收到错误消息
Expected operator name in operator declaration
在声明中。
自定义运算符只能使用一组受限的字符,有些运算符是保留的,不能重载。
Lexical Structure 中记录了精确的规则。特别是(强调):
Although you can define custom operators that contain a question mark (?), they can’t consist of a single question mark character only. Additionally, although operators can contain an exclamation mark (!), postfix operators can’t begin with either a question mark or an exclamation mark.
还有
- 你的运算符是 generic, 所以你必须用
<T>
, 声明 T
作为占位符类型
- 函数不能是
static
除非在类型中定义。
工作示例:
postfix operator =!!
postfix func =!! <T> (optionalValue: Optional<T>) -> T {
// realization
}
这是一个例子
//Define a operator
prefix operator √
//create a function and perform the operation.
prefix func √(lhs: Double) -> Double {
return sqrt(lhs)
}
//Do operation
let someVal:Double = 25
let squareRoot = √someVal // result is 5
我正在尝试创建自己的自定义运算符!!
postfix operator !! //error
static postfix func !! (optionalValue: Optional<T>) -> T {
// realisation
}
我收到错误消息
Expected operator name in operator declaration
在声明中。
自定义运算符只能使用一组受限的字符,有些运算符是保留的,不能重载。 Lexical Structure 中记录了精确的规则。特别是(强调):
Although you can define custom operators that contain a question mark (?), they can’t consist of a single question mark character only. Additionally, although operators can contain an exclamation mark (!), postfix operators can’t begin with either a question mark or an exclamation mark.
还有
- 你的运算符是 generic, 所以你必须用
<T>
, 声明 - 函数不能是
static
除非在类型中定义。
T
作为占位符类型
工作示例:
postfix operator =!!
postfix func =!! <T> (optionalValue: Optional<T>) -> T {
// realization
}
这是一个例子
//Define a operator
prefix operator √
//create a function and perform the operation.
prefix func √(lhs: Double) -> Double {
return sqrt(lhs)
}
//Do operation
let someVal:Double = 25
let squareRoot = √someVal // result is 5