Swift numerics and CGFloat (CGPoint, CGRect, etc.)

后端 未结 3 615
轻奢々
轻奢々 2020-12-01 02:07

I\'m finding Swift numerics particularly clumsy when, as so often happens in real life, I have to communicate with Cocoa Touch with regard to CGRect and CGPoint (e.g., becau

3条回答
  •  无人及你
    2020-12-01 02:13

    Explicitly typing scale to CGFloat, as you have discovered, is indeed the way handle the typing issue in swift. For reference for others:

    let scale: CGFloat = 2.0
    let r = self.view.bounds
    var r2 = CGRect()
    r2.size.width = r.width * scale
    

    Not sure how to answer your second question, you may want to post it separately with a different title.

    Update:

    Swift creator and lead developer Chris Lattner had this to say on this issue on the Apple Developer Forum on July 4th, 2014:

    What is happening here is that CGFloat is a typealias for either Float or Double depending on whether you're building for 32 or 64-bits. This is exactly how Objective-C works, but is problematic in Swift because Swift doesn't allow implicit conversions.

    We're aware of this problem and consider it to be serious: we are evaluating several different solutions right now and will roll one out in a later beta. As you notice, you can cope with this today by casting to Double. This is inelegant but effective :-)

    Update In Xcode 6 Beta 5:

    A CGFloat can be constructed from any Integer type (including the sized integer types) and vice-versa. (17670817)

提交回复
热议问题