Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Swift While loop check Int values

I have a While loop that doesn't seem to be working. I am asking it to check one Int Value against two others but I am shown the following error message: "Type 'Int' does not conform to protocol 'BooleanType'"

Here is the loop:

            while randomIndex == itemOneNumber||itemTwoNumber {
            randomNumber()
            }

However this seems to be working

            while randomIndex == 5||7 {
            randomNumber()
            }

Hey Tom,

I'm not so sure about it. But I think you should write the code like this:

while randomIndex == itemOneNumber || randomIndex == itemTwoNumber {
randomNumber()
}

Does this help?

Tried my both ways in a playground and it seems that this was the problem with your code. My solution made the loop work for me.

Thats perfect! Thank you

2 Answers

while randomIndex == itemOneNumber || randomIndex == itemTwoNumber {
randomNumber()
}

Thanks to Manuel Schulze

I don't know if you understand why this has to be like this. If you do it my way it's the same as

while (randomIndex == itemOneNumber) || (randomIndex == itemTwoNumber) {...}

Your way it was like while (randomIndex == itemOneNumber) || (itemTwoNumber) {...} and the second term evaluates always as true so the loop is always running and not working properly.

I hope this helps you to understand why it has to be like I did.

Greetings

Yes that is very helpful. Thank you. The thing that I couldn't work out is why it was working the second time with the integer values entered?

That's logical too. Swift is type safe. That means it prevents you from using an Int-Value at an "bool-spot".

Example:

var t = 1 // t gets interpreted as an Int Value. You can't do something like: if t { //your stuff }

because there has to be a conditional. So a bool value or a comparison is allowed here.

But if you do something like

if 3 { // your stuff }

the "3" will be interpreted as an Bool value and so the compiler will understand this statement as an true value. So this works.

For more information: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

Hope I could help you.

Yes that is fantastic! I understand now. Thanks again.