drinking drinking - 1 year ago 62
Swift Question

How can I deal with operation between Int and CGFloat?

In Objective-C I can do the following operation:

Objective-C code:

CGFloat width = CGRectGetWidth(mView.bounds);
CGFloat total = width*[myArray count];

but in Swift, it will raise an error:

Could not find an overload for '*' that accepts the supplied arguments

How can I avoid this situation elegantly?

Answer Source

First, let's create some demo data

let array: NSArray = ["a", "b", "c"] //you could use a Swift array, too
let view = UIView() //just some view

Now, everything else works almost the same way as in Obj-C

let width: CGFloat = CGRectGetWidth(view.bounds)

or simply

let width = CGRectGetWidth(rect) //type of the variable is inferred

and total:

let total = width * CGFloat(array.count)

Note that we have to add a CGFloat cast for array.count. Obj-C would implicitly cast NSUInteger to CGFloat but Swift has no implicit casts, so we have to add an explicit one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download