Aim is to create an operator
We start by declaring an infix operator
Now we provide a definition for the operator using a generic function.
That’s it!
The following swift powers have been tested in the snippet above
1. Custom operators
2. In-out variables
3. Generic functions
We can test the operator like:
Do notice that the operands of the operator
Edit: From +Rogier Pinkers's comment, the implementation for the operator has been changed with the inbuilt function to exchange two variables. Thanks +Rogier Pinkers!
<-> to exchange two variables. The two variables can be of any type, but they should be of the same type (Obviously!).We start by declaring an infix operator
<->infix operator <-> {}Now we provide a definition for the operator using a generic function.
func <-><T>(inout a: T, inout b: T) {
swap(&a, &b)
}
That’s it!
The following swift powers have been tested in the snippet above
1. Custom operators
2. In-out variables
3. Generic functions
We can test the operator like:
var a = 2, b = 4
a 2
b 4
a<->b
a 4
b 2
var ab = "a", ba = "b"
ab a
ba b
ab<->ba
ab b
ba a
Do notice that the operands of the operator
<-> should be declared variable (var) for the exchange to work.Edit: From +Rogier Pinkers's comment, the implementation for the operator has been changed with the inbuilt function to exchange two variables. Thanks +Rogier Pinkers!
No comments:
Post a Comment