Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : Useless default value for Optional?

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 ?

like image 417
Sylver Avatar asked May 10 '26 09:05

Sylver


1 Answers

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
like image 163
Martin R Avatar answered May 12 '26 23:05

Martin R