LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Question: Re How to Handle Missing Data with Optionals (Day 14)

Forums > 100 Days of SwiftUI

In Paul's example of squaring numbers:

func square(number: Int) -> Int {
    number * number
}

if let unwrappedNumber = number {
    print(square(number: unwrappedNumber))
}

is it better or common practice to do the unwrapping in the function definition like this? why or why not?

 func square(number: Int?) -> Int {
    if let unwrappedNumber = number {
       return unwrappedNumber * unwrappedNumber
    } else {
        return 0
    }
}

2      

If you allow a nil value to be passed into the function, what does that mean? How does one square a nil? The correct answer is not 0, because you cannot square a nil value. It doesn't make any sense, therefore, to allow a nil to be passed in and you should make sure you have an actual Int before calling the square function.

2      

Thanks for the response - while I agree that the return may not be the right one, that is not the question - you can return however you want by changing the code in the 'else' block - so I still don't have my answer -

2      

@mplsrich retorts:

so I still don't have my answer

@rooster has answered 100s of questions in these forums. His answers are awesome and address the issue.

Some folks give you the direct answer. But this is not ChatGPT. This is a learning site. I can see the correct answer in @rooster's response. This is something for you to think about and learn.

If you have a box in your kitchen labeled "Sausage Maker", perhaps you're expected to only add meat parts and spices into the box and it will produce nice sausage.

Why even try to add fruit? You're not going to get a smoothie. The box will just fail, and you'll damage your sausage maker.
Why even try to add vegetables? You're not going to get a salad. The box will just fail.

If you have a function in your code named squareRoot, why attempt to feed it a String? Why attempt to feed it a nil value?

The compiler will catch incorrect data (Booleans, Strings, nils) during compile time.

2      

To answer your second question:

is it better or common practice to do the unwrapping in the function definition like this? why or why not?

A better concept is to use the guard statement. This is taught in several lessons after Day 12. Stay tuned.

For a sneek peek see -> Guarding the Gates

Keep coding

2      

I agree with @roosterboy not to pass in a optional, however some cases it unavoidable so you could do this

func square(number: Int?) -> Int {
    guard let number else {
        fatalError("Unable to unwrap Int")
    }

    return number * number
}

print(square(number: 10))

2      

however some cases it unavoidable

This is the kind of thing where you should always check that you have a valid value before calling the function.

let aNumber = //do something that gives you an Optional<Int>
if let aNumber = aNumber {
    print(square(aNumber))
} else {
    print("cannot square a nil")
}

nil is a nonsensical value to pass into a square function and I would consider it a programmer error to do so.

3      

nil is a nonsensical value to pass into a square function

I would not being doing a square function that would be able to take a nil value. However there are cases that other value are optional (not necessary passed in but created) which you have no control and then you can check if it has a value before running the rest of the method using a guard let.

2      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.