In my project I have two needs that can be handled by one of my functions. I figured that an optional parameter would be the best way for that one function to handle two different needs.
What am unsure of is the proper syntax for checking the optional parameter. Below is the way I figured would be proper, but since am still green I wanted to double check. Maybe there’s a cleaner way? Or maybe there’s something inherently wrong with the way I am using it below.
func collectBuffers(sample: Bool?) {
...
if sample != nil, sample == true {
...
}
}
Your if sample != nil
is doing nothing in your code. Delete it. You can just say
if sample == true {
If sample
is nil
, or non-nil
but false
, the test will fail, as desired.
In my opinion this is the only situation in which you may compare something to true
, i.e. because it is not a Boolean (it’s an Optional wrapping a Boolean). In your original code, where you actually want to ask whether sample
is nil
, I would insist on your writing it this way:
if let sample, sample {
The if let
unwraps sample
safely, and now you do have a Bool — and there is no need to compare it against true
, as you are already saying if
and sample
is a Bool at this point.
3