Hello I have a problem with my Swift code.
In my application some
SKLabelNodes are supposed to have their y coordinate set to
CGRectGetMaxY(self.frame) - (nodes[i].frame.size.height / 2 + 30) * (i + 4)
var i:Int = 0
is a counter.
It works perfectly fine if instead of
(i + 4) I just give it a literal value e.g.
5 or even
(i == 0? 4 : 5) (just to see on two consecutive integers if the formula is correct itself).
But when I go with any variable or constant or expression containing one, it displays an error "CGFloat is not convertible to Int". It seems completely illogical, because
4 is an integer and so is
i and even
(i + 4), in which case changing
i shouldn't change the whole expression's type.
Can anyone explain why do I get this error and how can I possibly solve it?
Thanks in advance.
You have already explained and solved the matter perfectly. It's simply a matter of you accepting your own excellent explanation:
It works perfectly fine if ... I just give it a literal value ... But when I go with any variable or constant or expression containing one, it displays an error "CGFloat is not convertible to Int".
Correct. Numeric literals can be automatically coerced to another type, such as CGFloat. But variables cannot; you must coerce them, explicitly. To do so, initialize a new number, of the correct type, based on the old number.
So, this works automagically:
let f1 : CGFloat = 1.0 let f2 = f1 + 1
But here, you have to coerce:
let f1 : CGFloat = 1.0 let f2 = 1 let f3 = f1 + CGFloat(f2)
It's a pain, but it keeps you honest, I guess. Personally I agree with your frustration, as my discussion here will show: Swift numerics and CGFloat (CGPoint, CGRect, etc.) It is hard to believe that a modern language is expected to work with such clumsy numeric handling, especially when we are forced against our will to bang into the Core Graphics CGFloat type so frequently in real-life Cocoa programming. But that, it seems, is the deal. I keep hoping that Swift will change in this regard, but it hasn't happened so far. And there is a legitimate counterargument that implicit coercion, which is what we were doing in Objective-C, is dangerous (and indeed, things like the coming of 64-bit have already exposed the danger).