I'm creating a function like this :
func foo(bar: UInt? = 0) {
let doSomething = someOtherFunc(bar!)
}
If i'm passing to foo() a nil value, i'm expecting the default value of 0 to be used instead while unwrapping it, but rather than that i'm getting the usual error unexpectedly found nil while unwrapping an Optional value
Where am I wrong here ?
The default value = 0 is only used if you don't provide an argument
for the optional parameter:
func foo(bar: UInt? = 0) {
println(bar)
}
foo(bar: nil) // nil
foo(bar: 1) // Optional(1)
foo() // Optional(0), default value used
If your intention is to replace a passed nil value by 0
then you can use the nil-coalescing operator ??:
func foo(bar: UInt?) {
println(bar ?? 0)
}
foo(nil) // 0
foo(1) // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With