Commutative Operators

suggest change

This custom operator multiplies a CGSize by a CGFloat. CGSize.init takes width then height, and 20 is an Int, so it does not match CGFloat.

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(width: 200, height: 100)
let sizeB = 1.1 * sizeA         // CGSize(width: 220, height: 110)

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

let sizeC = sizeB * 1.1         // error until the overload below exists

But it’s simple enough to add:

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

Now the operator is commutative.

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

Feedback about page:

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



Table Of Contents