Trigonometric functions don't play nice with Core Graphics in Swift

Originator:frank
Number:rdar://17473492 Date Originated:2014-06-26
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode 6 Beta 2
Classification: Reproducible:
 
Summary:
Using functions like sin, cos, sqrt and abs in Swift with CGFloats requires way too much typecasting.

Steps to Reproduce:
import UIKit

func distance(p1: CGPoint, p2: CGPoint) -> CGFloat {
    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2))
}

Expected Results:
Should return the distance between the two points. Works fine in a playground, but give the following error in compiled code:

  'NSNumber' is not a subtype of 'CGFloat'

If you wrap the result in a CGFloat cast, the error changes to:

  Could not find an overload for '+' that accepts the supplied arguments

So let's try overflowing addition/subtraction:

  Could not find an overload for 'init' that accepts the supplied arguments

Let's try removing the CGFloat cast:

  Cannot convert the expression's type 'CDouble' to type 'CDouble'

?!

Here's what finally worked:

func distance(p1: CGPoint, p2: CGPoint) -> CGFloat {
    return CGFloat(sqrt(pow(CDouble(p1.x - p2.x), 2) + pow(CDouble(p1.y - p2.y), 2)))
}


Actual Results:
Ideally the original writing should work not just in playgrounds, but also in compiled code:

func distance(p1: CGPoint, p2: CGPoint) -> CGFloat {
    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2))
}

There probably needs to be a standard Swift math library that adds trig functions that take native Float and Double types and return the same, or perhaps take any numeric type using generics.  

Version:
Xcode 6 Beta 2

Notes:


Configuration:


Attachments:

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!