Swiftlint: Prefer `CGFloat.pi` to `CGFloat(M_PI)`

Created on 16 Jan 2017  路  8Comments  路  Source: realm/SwiftLint

Swift supports CGFloat.pi for a CGFloat version of 蟺 as opposed to a Double. It also appears that M_PI is being deprecated.

It would be good in the obvious cases where the developer wants a CGFloat version of 蟺 to detect and autocorrect to use the new Swift-y constant, avoid the typecast, and make the code more readable.

This may make sense as an extension of legacy_constant?

For reference:

enhancement

Most helpful comment

It's worth noting that CGFloat(M_PI) is very subtly different from CGFloat.pi on platforms where CGFloat is an alias of Float. Float.pi is 0x1.921fb4p1, but Float(Double.pi) is 0x1.921fb6p1. This is deliberate; 蟺 rounded to the nearest Float rounds up, outside the interval [0,蟺], which sometimes results in subtle bugs. So this change is more likely to fix bugs than cause them, but it's still something to be aware of.

All 8 comments

This may make sense as an extension of legacy_constant?

Makes sense for me!

Hmmm... this may be better off in a separate rule. 馃

The CGFloat.pi (and Float.pi) are only available in Swift 3+.

Also CGFloat(M_PI) results in two identifiers from SourceKitten, not one. So it's a different matching pattern than all of the rest of the legacy constants.

I think semantically it makes more sense to be the same rule, even if the implementation is a bit different.

You can use SwiftVersion.current to switch on the Swift version.

It's worth noting that CGFloat(M_PI) is very subtly different from CGFloat.pi on platforms where CGFloat is an alias of Float. Float.pi is 0x1.921fb4p1, but Float(Double.pi) is 0x1.921fb6p1. This is deliberate; 蟺 rounded to the nearest Float rounds up, outside the interval [0,蟺], which sometimes results in subtle bugs. So this change is more likely to fix bugs than cause them, but it's still something to be aware of.

@marcelofabri Sounds good. I'll continue down my the path of my initial implementation. I should have a PR raised later today.

This appears to have introduced a bug where autocorrect is converting CGFloat(M_PI) to CGFloat.pi in Swift 2.3 code.

@raid5 I couldn't reproduce it. Could you fill an issue with more details?

Was this page helpful?
0 / 5 - 0 ratings