Hi, guys I need help solving this question that involves function and optionals

I'm done with the first part, I need help with second question that involves updating the function to return an Int. Ive tried to solve it but what I get is an error

  1. If an app asks for a user's age, it may be because the app requires a user to be over a certain age to use some of the services it provides. Write a function called checkAge that takes one parameter of type String. The function should try to convert this parameter into an Int value and then check if the user is over 18 years old. If he/she is old enough, print "Welcome!", otherwise print "Sorry, but you aren't old enough to use our app." If the String parameter cannot be converted into an Int value, print "Sorry, something went wrong. Can you please re-enter your age?" Call the function and pass in userInputAge below as the single parameter. Then call the function and pass in a string that can be converted to an integer.

  2. Go back and update your function to return the age as an integer. Will your function always return a value? Make sure your return type accurately reflects this. Call the function and print the return value.

func checkage(age: String)->Int?
if let age_type = Int(age)
if age_type > 18 {
return "Welcome!"
else if age_type < 18 {
return"Sorry, but you aren't old enough to use our app."
else {
return "Sorry, something went wrong. Can you please re-enter your age?"
return age_type


error: 3. Exercise - Functions and Optionals.xcplaygroundpage:20:12: error: use of unresolved identifier 'age_type'
return age_type

  1. The use of unresolved identifier 'age_type' error it's because age_type it's only declared within the if-let block; outside that block, there's no age_type.

  2. Since you can't return age_type outside the if-left block, you need to decide which value to return in case the Int casting fails. i.e, you could return -1, nil, etc.

The Optionals and Optional Binding sections from the Language Guide would help you understand more about what is happening here and also will help you decide what you should return when you can't convert the given String to Int.

If you have further questions, don't hesitate to ask.


Terms of Service

Privacy Policy

Cookie Policy