Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - "CGFloat is not convertible to Int" when trying to calculate an expression

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)

Where

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 4 to 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...