Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading "." produces errors

Tags:

swift

I can't seem to overload "." and not sure if it's a compiler bug or something I'm doing:

@infix func . (a: Int, b: Int) -> Int {
  return a * b
}

I get the errors:

Expected identifier in function declaration Braced block of statements is an unused closure

like image 566
Brandon Williams Avatar asked Mar 24 '26 05:03

Brandon Williams


2 Answers

You can't overload '.' It's a reserved token for the language. You can however overload the .. and ... operators.

Operators are made up of one or more of the following characters: /, =, -, +, !, , %, <, >, &, |, ^, ~, and .. That said, the tokens =, ->, //, /, */, ., and the unary prefix operator & are reserved. These tokens can’t be overloaded, nor can they be used to define custom operators.

Language Reference

like image 85
Connor Avatar answered Mar 27 '26 09:03

Connor


Swift does allow the definition and overload of custom operators, but it only allows certain characters to be considered operators.

Operators are made up of one or more of the following characters: /, =, -, +, !, *, %, <, >, &, |, ^, ~, and .. That said, the tokens =, ->, //, /*, */, ., and the unary prefix operator & are reserved. These tokens can’t be overloaded, nor can they be used to define custom operators.

It is therefore illegal to try to overload the period operator, though it can be used as part of another custom operator.

like image 26
zneak Avatar answered Mar 27 '26 10:03

zneak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!