Commutative Operators

suggest change

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents