‘CGFloat’ is not convertible to ‘UInt8' and other CGFloat issues with Swift and Xcode 6 beta 4

前端 未结 4 1230
孤街浪徒
孤街浪徒 2020-12-11 02:09

In case this illuminates the problem, here\'s the original Objective-C code.

int x = (arc4random()%(int)(self.gameView.bounds.size.width*5)) - (int)self.game         


        
相关标签:
4条回答
  • 2020-12-11 02:17

    Since Swift doesn't have implicit type conversions, you must specify all the type conversions that take place. What makes this case particularly tedious, is that currently Swift seems to lack direct conversions between CGFloat and types such as UInt32, and you must go through an intermediate type as you've discovered.

    In the end, two double conversions are needed for the arc4random_uniform:

    let bounds = CGRectMake(0.0, 0.0, 500.0, 500.0)
    var x = CGFloat(UInt(arc4random_uniform(UInt32(UInt(bounds.size.width) * 5))))
    x -= bounds.size.width * 2
    let center = CGPointMake(x, -bounds.size.height)
    
    0 讨论(0)
  • 2020-12-11 02:26

    Had the same problem ... try wrapping

    arc4random_uniform 
    

    with

    Int()
    

    like

    Int(arc4random_uniform)
    

    this worked for me ... don't know why Swift/Xcode hast problems converting unsigned INT's

    0 讨论(0)
  • 2020-12-11 02:31

    @Arkku provided the correct solution, so the one-liner for x is...

    let x = CGFloat(UInt(arc4random_uniform(UInt32(UInt(self.gameView.bounds.size.width) * 5)))) - self.gameView.bounds.size.width * 2
    

    As of Xcode 6 beta 5, you can still use an intermediate conversion if you want and your code will continue to work. However, it is no longer necessary, so the following now works as expected.

    let x = CGFloat(arc4random_uniform(UInt32(self.gameView.bounds.size.width * 5))) - self.gameView.bounds.size.width * 2
    

    Since the original question is only relevant to Xcode 6 beta 4, what is the proper way to handle the question? Is there a historical mark? Should it be deleted?

    0 讨论(0)
  • 2020-12-11 02:42

    TL;DR simple shortcuts cause HCF: Halt and Catch Fire bugs

    Note that there are some obvious work legal work arounds like implementing conversion to and from CGFloat:

    Totally legal, but don't do this:

    extension Float {
        func __conversion() -> CGFloat { return CGFloat(self) }
    }
    
    extension CGFloat {
        func __conversion() -> Float { return Float(self) }
        func __conversion() -> Double { return Double(self) }
    }
    
    extension Double {
        func __conversion() -> CGFloat { return CGFloat(self) }
    }
    

    I did not notice when typing, but later my machine kept overheating and hanging and SourceKit went to 300-500%, and the swift proceess + kernel_task took up 10+ gigs of RAM, consuming all that was left of my 16 gigs. It took a long time to trace it back to this - it wasn't swift.

    0 讨论(0)
提交回复
热议问题