Swift Language Advanced Operators Commutative Operators

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Let's add a custom operator to multiply a CGSize

func *(lhs: CGFloat, rhs: CGSize) -> CGSize{
    let height = lhs*rhs.height
    let width = lhs*rhs.width
    return CGSize(width: width, height: height)

Now this works

let sizeA = CGSize(height:100, width:200)    
let sizeB = 1.1 * sizeA         //=> (height: 110, width: 220)

But if we try to do the operation in reverse, we get an error

let sizeC = sizeB * 20          // ERROR

But it's simple enough to add:

func *(lhs: CGSize, rhs: CGFloat) -> CGSize{
    return rhs*lhs

Now the operator is commutative.

let sizeA = CGSize(height:100, width:200)    
let sizeB = sizeA * 1.1              //=> (height: 110, width: 220)

Got any Swift Language Question?