SOLVED: Checkpoint 9

Hey fellow HWSters, Here is my completed code for Checkpoint 9. I did it in a fairly simple way, so if you have any sugestions on how to improve it please let me know.

``````let arrayOfIntegers: [Int]? = nil

let randomInteger = arrayOfIntegers?.randomElement() ?? .random(in: 1...100)
print(randomInteger)
``````

2

Matthew is looking for feedback on Challenge 9.

I did it in a fairly simple way, so if you have any sugestions on how to improve it please let me know.

``````// You're setting a constant. This will never hold anything but nil.
let arrayOfIntegers: [Int]? = nil

// This line of code will never execute the first part of the clause.
// This is because arrayOfIntegers will always be nil.
let randomInteger = arrayOfIntegers?.randomElement() ?? .random(in: 1...100)``````

The challenge was to write a `function`. I am not sure you met the requirements of this challenge. You didn't write a `function`, and your `arrayOfIntegers` is a `constant` that won't be anything but `nil`.

Try again?

2

Hey @Obelix, Thank you for the feedback and here is my updated Checkpoint 9. Cheers :)

``````var arrayOfIntegers: [Int]? = nil

func randomInteger(arrayOfIntegers: [Int]?) -> Int {
return arrayOfIntegers?.randomElement() ?? .random(in: 1...100)
}

print(randomInteger(arrayOfIntegers: [1, 2, 7, 9]))``````

2

On his second try Matthew codes:

``````// var arrayOfIntegers: [Int]? = nil  // Good use case! But you never test this.
// rename to:
var nilArrayOfIntegers: [Int]? = nil // Pass this to your function as a test case!

func randomInteger(arrayOfIntegers: [Int]?) -> Int {
return arrayOfIntegers?.randomElement() ?? .random(in: 1...100)
}

print(randomInteger(arrayOfIntegers: [1, 2, 7, 9]))

// Add this test case to get full points!
print(randomInteger(arrayOfIntegers: nilArrayOfIntegers) // Pass in the nil array from above.``````

Nicely done!

Keep coding!

2

Thanks, @Obelix for the suggestions! Here is my updated code.

``````var nilArrayOfIntegers: [Int]? = nil

func randomInteger(arrayOfIntegers: [Int]?) -> Int {
return arrayOfIntegers?.randomElement() ?? .random(in: 1...100)
}

print(randomInteger(arrayOfIntegers: [1, 2, 7, 9]))
print(randomInteger(arrayOfIntegers: nilArrayOfIntegers))``````

2

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

You are not logged in