I am +1 for this proposal.
I think this proposal presents a focused solution that provides a significant ergonomic improvement when working with common frameworks that have
CGFloat APIs, including Core Graphics, Core Animation, and SwiftUI.
The proposed change allows ‘naturally-written’ Swift code without type annotations to work with
CGFloat APIs without manual type conversions. I believe this will encourage the use of the preferred Swift floating point type
Double and significantly improve call site clarity. So, I think this proposal fits very well with the feel and direction of Swift.
I am not well versed with the internals of the type checker, but I trust those who are expert will chime in if this proposed change causes significant performance or other issues.
I followed and contributed to the pitch thread for this proposal.
One potential issue is that on platforms with 32-bit
CGFloat values, such as watchOS, there is a loss of precision when narrowing from
In practice, I don’t believe this will be a significant issue, since APIs that use
CGFloat must already be suitable for use with 32-bit float values.
In addition, the Core Graphics overlay for Swift introduced five or six years ago adds initializers for
CGRect that take
On platforms with 32-bit
CGFloat, these initializers have been doing a narrowing conversion for a half a decade or so, and have not seemed to cause any widespread issues.
Finally, it is generally better to work in the higher precision type and only lose precision when necessary. This proposal enables doing so without effort by the developer:
- Declared constants and variables are
Double by default.
CGFloat values pulled from structs like
CGSize are automatically promoted to
Double when used in a calculations with
- Passing resulting
Double values into API that takes
CGFloat performs the narrowing.
So, the most straightforward way of writing the code also leads to all intermediate calculations using
Double, with narrowing only happening when API calls require it.
That all said, I do think it would be beneficial to add more detail in the proposal about the considerations regarding 32-bit
CGFloat, especially since evolution proposals also serve as a way for developers to understand the change in the future.
One effect of this proposal, I think, is that it will greatly reduce or eliminate the need for declaring variables of type
CGFloat in client code. All calculations can be done in
Double. In fact,
CGFloat variables become a bit of a red flag that unnecessary or unintentional narrowing may be happening on 32-bit platforms.
I hope this proposal is approved. I think it will make code clearer, easier for newcomers, and more enjoyable to write.