1

I am trying to write this in Swift (I am in step 54). In a UICollectionViewLayout class I have a function setup function

func setup() {
    var percentage  = 0.0
    for i in 0...RotationCount - 1 {

        var newPercentage = 0.0

        do {
            newPercentage = Double((arc4random() % 220) - 110) * 0.0001
            println(newPercentage)
        } while (fabs(percentage - newPercentage) < 0.006)

        percentage = newPercentage

        var angle = 2 * M_PI * (1 + percentage)
        var transform = CATransform3DMakeRotation(CGFloat(angle), 0, 0, 1)
        rotations.append(transform)
    }
}

Here is how the setup function is described in the tutorial

First we create a temporary mutable array that we add objects to. Then we run through our loop, creating a rotation each time. We create a random percentage between -1.1% and 1.1% and then use that to create a tweaked CATransform3D. I geeked out a bit and added some logic to ensure that the percentage of rotation we randomly generate is a least 0.6% different than the one generated beforehand. This ensures that photos in a stack don't have the misfortune of all being rotated the same way. Once we have our transform, we add it to the temporary array by wrapping it in an NSValue and then rinse and repeat. After all 32 rotations are added we set our private array property. Now we just need to put it to use.

When I run the app, I get a run time error in the while (fabs(percentage - newPercentage) < 0.006) line.

enter image description here

the setup function is called in prepareLayout()

override func prepareLayout() {
    super.prepareLayout()
    setup()
    ...
}

Without the do..while loop, the app runs fine. So I am wondering, why?

ielyamani
  • 17,807
  • 10
  • 55
  • 90

2 Answers2

0

Turns out I had to be more type safe

newPercentage = Double(Int((arc4random() % 220)) - 110) * 0.0001
ielyamani
  • 17,807
  • 10
  • 55
  • 90
0

This must be a Swift bug. That code should NOT crash at runtime. It should either give a compiler error on the newPercentage = expression or it should correctly promote the types as C does.

Bruce1q
  • 504
  • 4
  • 8