Confusion due to Swift lacking implicit conversion of CGFloat

后端 未结 4 615
你的背包
你的背包 2020-12-16 02:10

Trying to do arithmetic in a function that returns `CGFloat, I get an error:

Couldn\'t find overload for \'/\' that accepts supplied arguments

4条回答
  •  囚心锁ツ
    2020-12-16 02:45

    This is a problem with double to float conversion.

    On a 64-bit machine, CGFloat is defined as double and you will compile it without problems because M_PI and x are both doubles.

    On a 32-bit machine, CGFloat is a float but M_PI is still a double. Unfortunately, there are no implicit casts in Swift, so you have to cast explicitly:

    return (CGFloat(M_PI) * (x) / 180.0)
    

    The type for 180.0 literal is inferred.

    In Swift 3

    M_PI is deprecated, use CGFloat.pi instead:

    return (x * .pi / 180.0)
    

提交回复
热议问题