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

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?