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
Jamie Baker
5,703 Pointsissue with for-loops
am just practicing using for-loops, and have created a function to test if a number passed in is a prime number or not. for some reason whenever i pass a value to the function to test it, the 'found' value always comes up as false, regardless of what I pass in. Help much appreciated:
func prime(number: Int) -> Bool {
var arr = [2,3,5,7,11]
var found: Bool?
for n in arr {
if (n == number) {
found = true
} else {
found = false
}
}
return found!
}
2 Answers
Steve Hunter
57,712 PointsHi Jamie,
The function is testing for two outcomes - those have total scope (there are no other possible outcomes) and mutually exclusive (if one occurs the other cannot). So, while the purists may say adding the return of false inside the else part is clearer code, and they may be right, the return of false must also occur outside of the for loop and if clause else the compiler will get twitchy. That's a duplication of code which can't add clarity.
When the code execution fails the if test for every number in your array the function must return false. Getting more complex than that serves no purpose, in my opinion.
Hope that helps!
Steve.
Steve Hunter
57,712 PointsYep - it'll do that. Unless you pass in 11.
That's because you're looping through all the prime possibilities so will always test whether n == 11 last. If number isn't 11, the result is false.
Try returning immediately:
func prime(number: Int) -> Bool {
var arr = [2,3,5,7,11]
for n in arr {
if (n == number) {
return true
}
}
return false
}
I hope that makes sense!
Steve.
Steve Hunter
57,712 PointsThere's some more loops and prime number testing in this post too.
Jamie Baker
5,703 Pointscheers Steve. one more question though, is it OK to return False like that outside of the for-loop and without an 'else' term?