Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

optional Int that has a 50% chance to be nil ?

Can Anyone explain how to to this? I'm super confused.

  • Create an optional Int that has a 50% chance to be nil and a 50% chance to be a random value between 1 and 10
  • Convert the variable to a string WITHOUT force-unwrapping.
  • If nil, print "The variable is nil" to the console as part of your optional binding

What I have so far.

var optionalInt:Int?
var randomInt = Int(arc4random_uniform(2))

if(randomInt == 0){

    optionalInt = Int(arc4random_uniform(11))
 }
 else{
    if let intValue = optionalInt, if String? myString = String(intValue)
     {
         print(myString)
     }
 }

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

I am going to use the ternary operator to create a optional Int:

var optionalInt: Int? = Int(arc4random_uniform(2)) == 0 ? nil : Int(arc4random_uniform(11))

I will then use an if-let statement to see if the variable is ni and then do the printingl:

if let int = optionalInt {
    let string = String(int)
} else {
    print("The variable is nil")
}

This may or may not work. Could you add the link to the challenge in your question?