SWIFT: OPTIONAL’s useless default?

I am creating a function like this:

func foo(bar: UInt? = 0) {
let doSomething = someOtherFunc(bar!)
)

If I pass a zero value to foo(), I want to use the default value 0 when opening it, not when I unwrap one Unexpectedly found nil when Optional value. Unexpectedly found nil

Where did I go wrong?

Use the default value = 0 only if you don’t provide a parameter.
For optional Parameters:

func foo(bar: UInt? = 0) {
println(bar)
}

foo(bar: nil) // nil
foo(bar: 1) // Optional(1)
foo() // Optional(0), default value used

If you intend to replace the passed nil value with 0
then you can use the nil-coalescing operator??:

func foo(bar: UInt?) {< br /> println(bar ?? 0)
}

foo(nil) // 0
foo(1) // 1

< /p>

I am creating a function like this:

func foo(bar: UInt? = 0) {
let doSomething = someOtherFunc (bar!)
)

If I pass a zero value to foo(), I want to use the default value of 0 when opening it, instead of accidentally discovering when I unwrap an Optional value nil accidentally found nil

Where did I go wrong?

Use the default value = 0 only if you don’t provide a parameter.
For optional parameters:

func foo(bar: UInt? = 0) {
println(bar)
}

foo(bar: nil) // nil
foo(bar: 1) // Optional(1)
foo() // Optional(0), default value used

If you plan to replace the passed nil value with 0< br>Then you can use the nil-coalescing operator??:

func foo(bar: UInt?) {
println(bar ?? 0)
}

foo(nil) // 0
foo(1) // 1

Leave a Comment

Your email address will not be published.