Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
drinking Avatar asked Jun 07 '14 08:06

drinking


1 Answers

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.

like image 52
Sulthan Avatar answered Oct 04 '22 04:10

Sulthan