What is the best way to do math with CGFloats in fast?

I tried to execute a simple mathematical UIView diagram in Swift and tried the following line of code ...

var offset: CGFloat = (bounds.width / 2.0) - ((sortedSymptoms.count * bounds.height) / 2.0) 

and received the following error from the compiler:

 cannot invoke '-' with an argument list of type '(($T6), ($T17))' var offset: CGFloat = (bounds.width / 2.0) - ((sortedSymptoms.count * bounds.height) / 2.0) ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

A compiler error is not so useful, but it seems that there is a type conflict between Double, Int and CGFloat. I managed to compile this line by sending some explicit creations of CGFloats, but I cannot believe that this is the right way to do this.

 var offset: CGFloat = (bounds.width / CGFloat(2.0)) - ((CGFloat(sortedSymptoms.count) * bounds.height) / CGFloat(2.0)) 

What is the right way?

+5
source share
1 answer

This is a known issue in Swift, and the development team is working to improve the issue in CGFloat in particular. But at this time, yes, that’s how you write it.

Some follow-up from devforums (which can make you happy or sad, but at least rudely explains the current status): https://devforums.apple.com/message/1026028#1026028

Note that the main problem here is that the letter 2.0 does not force CGFloat , which may be what it should be. But count , most likely, will always require a purposeful throw. You cannot always safely convert between numeric types, and Swift intentionally forces you to consider every time you make these types of throws. But it should be possible to determine if the conversion is literally safe at compile time, so it should be fixed.

+7
source

Source: https://habr.com/ru/post/1203502/


All Articles