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 trialWill Seith
2,742 PointsDon't know how to check if integer is even or odd in Swift 2.0 except by evaluating with remainders.
``` Swift 2.0 ////// Quiz Work //////
// Need to check is each integer is a multiple of 7 or is an even number // then append integer to results array.
var results: [Int] = []
for n in 1...100 { // Enter your code below if n % 7 = 0 || n % 2 = 0 {results.append(n) } results++ } // End code }
// NOT function is suggested to check if n is even. Help?
```logicalOperators.swift
var results: [Int] = []
for n in 1...100 {
// Enter your code below
if results
// End code
}
3 Answers
Cindy Lea
Courses Plus Student 6,497 PointsThis is what theyre looking for:
var results: [Int] = []
for n in 1...100 { if (n % 7 == 0 && n % 2 != 0) { results.append(n) } }
Will Seith
2,742 PointsThank you, Cindy! I wa able to figure it out by experimenting a little bit, but the speedy response is appreciated. I was definitely missing a few glaring details.
William Li
Courses Plus Student 26,868 PointsI'd like to add a little to the discussion just to make the complete answer to your original question.
Don't know how to check if integer is even or odd in Swift 2.0 except by evaluating with remainders.
Divide by 2 and evaluate the resulted remainder is pretty much the standard way of checking for a number's odd/even property in almost any programming language, not just Swift.
There're exceptions of course, for instance, in Ruby programming language, the odd? & even? methods were built-in to the Integer class, in such case, you should just make use of 'em instead of doing the %2 math calculation for the sake of simplicity.
# sample ruby code
2.odd? #=> false
4.even? # => true
Ruby can do that, but Swift doesn't have the same utility.