Search code examples
iosiphoneswiftoperator-overloadingoperators

Advantage of using custom operators over methods in Swift


For achieving a particular functionality we use methods, but if we use a custom operator instead of using a method, What are advantages? I hear that it will increase the performance of code. I don’t know its true or not, I want some explanations.


Solution

  • A custom operator is a method, thus there is no performance difference.

    Opinion based:

    Using custom operators can highly improve readability if, and only if, the semantic can not be mistaken. For example:

    "str1 " + "str2" -> "str1 str2" is nicely readable and does what you actually expect.

    Do not use customized nor override operators if the semantic is not clear or can be mistaken. Also stick to the commonly known meaning of an operator, if there is any. Especially when overriding operators. An add functionality should not be implemented with an -operator obviously, but there are also not so obvious examples.