11
var w:Int  = Int(self.bounds.size.width / Float(worldSize.width))
var h:Int  = Int(self.bounds.size.height / Float(worldSize.height))

Error : 'CGFloat is not convertible to UInt8'

I researched this conver type and i found this one Convert Float to Int in Swift my code like this but not working any idea ?

Community
  • 1
  • 1
Gökhan Çokkeçeci
  • 1,388
  • 3
  • 16
  • 37

1 Answers1

31

In beta 4, CGFloat has become a new type. So you'd do:

var w:Int  = Int(self.bounds.size.width / CGFloat(worldSize.width))
var h:Int  = Int(self.bounds.size.height / CGFloat(worldSize.height))
DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • wouldn't it be even better to be explicit and use `ceilf` or `floorf` for the conversion, rather than just a cast to `Int`? – Anorak Aug 05 '14 at 11:52
  • @Anorak: … or `round`. That is up to the OP to decide: if fractions don't make any sense in his context, then it's good to use integer types instead of using floating point and trying to ensure they are integer. – DarkDust Aug 05 '14 at 11:56
  • @Anorak Be careful using ceilf or floorf with CGFloat. Your suggestion, e.g. `floorf(self.bounds.size.width / CGFloat(worldSize.width))` would work on 32-bit target, but not compile for a 64-bit target ("'CGFloat' is not convertible to 'Float'") as CGFloat is a double on 64-bit. Using the double versions, ceil or floor, would work on either target. – Matt Gibson Aug 06 '14 at 06:39
  • @MattGibson Yeah, I know. I've used `#import "tgmath.h"` in the past to be sure to get the correct types returned for such calculations. Unfortunately they don't work well with module support enabled (bug filed) – Anorak Aug 06 '14 at 08:53
  • 1
    @Anorak You might be okay going back to basics now. CGFloat has been expanded a lot, and now has specific floor and ceil operators defined on it, e.g. `func floor(x: CGFloat) -> CGFloat`, to help mitigate 32- vs. 64-bit differences. So just using floor and ceil and never worrying about floorf and ceilf should simply work as you'd expect in the latest beta, as long as you can use CGFloat throughout, which is usually possible. – Matt Gibson Aug 06 '14 at 09:12
  • 1
    @MattGibson I do use the system macros (CGFloat, NSInteger) everywhere so this is indeed the case for me. Thank you for the heads up. Appreciate it. – Anorak Aug 06 '14 at 09:14