Programming in Swift · Challenge: While Loops | Ray Wenderlich


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/12

Getting error : Type ‘Int’ has no member ‘random’

@dhruvil This is a new Swift 4.2 feature, so you need to download and install Xcode 10 beta 6 in order to make the playground run. Please let me know if you have any other questions or issues about the whole thing. Thank you!

1 Like

Hi,
I have question about the second challenge (While Loops).
May I know why we use !=6 instead of ==6 ? I’m very new in swift. Sorry for the trouble.

Hello everyone,

I would like to ask why in the “Extra challenge”, in the second way to do it, we write
while roll != 6 && count < 5
instead of count < 6.

Thank you so much

@anon16945610 You execute the repeat while loop as long as roll isn’t six, not as long as you roll only six in a row. Please let me know if you have any other questions or issues about the whole thing. Thank you!

@notationmaster You want to stop the repeat while loop after five iterations not six. Please let me know if you have any more questions or issues about the whole thing. Thank you!

1 Like

@notationmaster You use both of them because you want to simultaneously check whether the roll value isn’t six and if the count value is under 5. This allows you to stop the loop if either condition is not met. If it takes more than 5 rolls to reach a roll value of 6, then the loop exits without reaching 6. If the roll value reaches 6 before 5 rolls, the loop exits before reaching 5 rolls.

2 Likes

having a issue. I did everything as it says and its having trouble compiling. That being said I then opened the final product made by you guys. It had the same issue “Type ‘Int’ has no member ‘random’”

count = 0

var roll: Int = 0

repeat {

roll = Int.random(in: 1…6)

count += 1

// if count > 5 {

// break

// }

print(“After (count) roll(s), roll is (roll)”)

} while roll != 6 && count < 5

@lac_ekim What Xcode version are you using?

@shogunkaramazov Version 10.1 (10B61)

I must say sorry and ty @shogunkaramazov

I had the same question. What helped me was to think of it in terms of scope. In the “repeat scope”, the exit occurs when the count becomes 6 before executing another iteration. In the “while scope”, the exit occurs after the count is 5 because that also means that the 5th iteration has already occurred.