Declare operators as static functions instead of free functionsSW-R1015
Declaring operators as free functions in Swift can lead to several issues and make the code harder to read and maintain.
Cluttered Namespace: When operators are declared as free functions, they pollute the global namespace and make it harder to find other functions and variables. This can lead to naming conflicts, especially if multiple libraries define operators with the same name.
Inconsistency: Swift’s standard library defines many operators as static functions on the type they operate on. Declaring custom operators as free functions breaks this convention and can make the code harder to understand and remember.
Limited Functionality: Free functions cannot be overridden or accessed through inheritance, which limits their functionality. This can make it harder to extend the functionality of operators or customize them for specific use cases.
Inefficient Method Dispatch: When operators are declared as free functions, the Swift compiler has to perform dynamic method dispatch to determine the correct implementation to use. This can be slower than using a static function.
In summary, declaring custom operators as free functions can pollute the global namespace, break conventions, limit functionality, and lead to inefficient method dispatch. It is generally recommended to declare operators as static functions on the type they operate on.
Bad Practice
func +<T>(lhs: T, rhs: T) -> T {
// implementation
}
Recommended
static func +<T>(lhs: T, rhs: T) -> T {
// implementation
}