Swift, Apple’s programming language for iOS, macOS, watchOS, and tvOS, provides the ability to define custom operators. Custom operators allow developers to create their own symbols and rules for performing operations, improving the readability and clarity of their code. In this article, we will explore custom operators in Swift, defining and how they can improve code readability.
What are Custom Operators?
In Swift, operators are symbols or keywords that perform operations on variables and values. While Swift comes with tons of built-in operators, such as + for addition and * for multiplication, custom operators allow developers to introduce their own symbols for specific operations. This can lead to more concise and expressive code, making it easier to convey the intent of the operations being performed.
Defining Custom Operators
Custom operators allow developers to extend Swift’s capabilities by introducing new symbols for operations that are meaningful in their specific domain. To define a custom operator, you use the operator keyword followed by the operator’s symbol, and then you provide the implementation using functions.
Infix Custom Operator
An infix operator is placed between its operands. To declare an infix custom operator, we use the infix keyword along with the operator keyword.
Let’s create a simple example of an infix custom operator that concatenates two strings called <+>.
import Foundation
// Operator Declaration
infix operator <+>
// Operator Definition
func <+>(lhs: String, rhs: String) -> String {
return lhs + rhs
}
let name: String = "Edward " <+> "Stephen Jr."
print(name)
In this example, we’ve defined the <+> operator with the infix keyword, indicating that it is an infix operator placed between its operands.
The implementation of the operator is done by declaring a function using the same symbol <+>. This function takes two parameters (lhs and rhs) representing the left and right operands and returns the result of the operation.
Prefix Custom Operator
A prefix operator is placed before its operand. To declare a prefix custom operator, we use the prefix keyword along with the operator keyword. Here’s an example of a prefix custom operator that adds 1 to an integer value called ++:
import Foundation
// Operator Declaration
prefix operator ++
// Operator Definition
prefix func ++(value: inout Int) -> Void {
value += 1
}
var number: Int = 28
// Add 1 to number
++number
print(number) // Output: 19
In this example, the ++ operator adds 1 to an integer value. The associated function specifies the operation performed by the operator. Note the operator modifies the variable in-place, and it does not return anything.
Postfix Custom Operator
A postfix operator is placed after its operand. To declare a postfix custom operator, we use the postfix keyword along with the operator keyword. Here’s an example of a postfix custom operator that converts a percentage to its decimal equivalent called %:
import Foundation
// Operator Declaration
postfix operator %
// Operator Definition
postfix func %(value: Int) -> Double {
return Double(value) / 100
}
let percentage: Double = 35%
print(percentage) // Output: 0.35
In this example, the % operator converts a percentage to its decimal equivalent. The associated function defines the behavior of the postfix operator.
Precedence and Associativity
Custom operators in Swift can also specify their precedence and associativity, allowing developers to control how they interact with other operators. If you don’t specify the precedence group, it defaults to the DefaultPrecedence precedence group. Precedence is a numerical value that determines the order of evaluation, while associativity defines how operators of the same precedence level are grouped.
Let’s create an infix custom exponentiation operator (*) with higher precedence than multiplication () and addition (+).
import Foundation
// Operator Declaration
infix operator **: MultiplicationPrecedence
// Operator Definition
func **(base: Double, power: Double) -> Double {
return pow(base, power)
}
let result: Double = 2.0 ** 2.0 * 4.0 + 1.0
print(result) // Output: 17
In this example, the ** operator has been declared with MultiplicationPrecedence to ensure it has higher precedence than the * and + operators. Visit the Operator Declarations section in the Apple Developer Documentation for more information about precedence groups.
Conclusion
Custom operators in Swift offer a powerful mechanism for tailoring the language to specific needs, promoting expressive and readable code. Whether for arithmetic operations, domain-specific tasks, or unique scenarios, custom operators contribute to Swift’s versatility.
As you explore the world of custom operators, keep in mind the importance of clarity and adherence to established conventions. When used thoughtfully, custom operators can elevate the elegance of your code, providing a concise and expressive way to represent complex operations.
Related: