Chapter 3 mini exercise 1

“Create a constant called myAge and set it to your age. Then, create a constant named isTeenager that uses Boolean logic to determine if the age denotes someone in the age range of 13 to 19.”

my logic:

let myAge = 32

let isTeenager = 13…<19

When I try to compare myAge to isTeenager I get this error message: Binary operator ‘==’ cannot be applied to operands of type ‘Int’ and ‘Range’

my question:
how do you denote someones age in a specified range without using the … syntax? Any help is greatly appreciated. Thanks!

@mdotflow22 Thanks very much for your question!

You can try something like this:

if (13 ..< 19).contains(myAge) {
   isTeenager = true
} else {
   isTeenager = false
}

I hope this helps!

All the best!

Based on your logic:

Constant myAge is of type Int.
Constant isTeenager is of type Range.

You will get that error message if you try to evaluate a bool from comparing the two different types to see if they are equal (==)

myAge == isTeenager    // error

In addition to @syedfa 's solution :+1: , another way could be to compare myAge to isTeenager’s upper and lower bounds of it’s range.

isTeenager will resolve to true if both (&&) it’s conditions are true

let myAge = 32                                     // 32
let isOlderThan12 = myAge >= 13                    // true
let isYoungerThan20 = myAge <= 19                  // false

let isTeenager = isOlderThan12 && isYoungerThan20  // false

This can written more ‘swiftly’ like this:

let myAge = 32                                     // 32
let isTeenager = myAge >= 13 && myAge <= 19        // false

Cheers!
Rebecca

This topic was automatically closed after 166 days. New replies are no longer allowed.