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

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 4137 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.