Chapter 3: Behavior Subjects Example Error

In the func for CustomStringConvertible, I am getting an error with the following line of code:
print(label, event.element ?? event.error ?? event)

I get the following error:
Playground execution failed:

error: RxSwiftPlayground.playground:79:32: error: value of optional type 'Any?' must be unwrapped to a value of type 'Any'
    print(label, event.element ?? event.error ?? event)
                               ^

RxSwiftPlayground.playground:79:32: note: coalesce using '??' to provide a default when the optional value contains 'nil'
    print(label, event.element ?? event.error ?? event)
                               ^
                 (                                    ) ?? <#default value#>

RxSwiftPlayground.playground:79:32: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
    print(label, event.element ?? event.error ?? event)
                               ^
                 (                                    )!

I tried using code from the finished example but I get the same error. I am using using Xcode 10.1. I’m not sure if something has changed since Xcode 9, or if there is a better way to handle the Event type.

@scotteg Can you please help with this when you get a chance? Thank you - much appreciated! :]

Certainly! How can I help?

@ariopolis I asked the chapter’s author to help you :]

Hi,

Write the function like this:

func print<T: CustomStringConvertible>(label: String, event: Event<T>) {

guard let element = event.element else {

print(label, event.error ?? event)

return

}

print(label, element)

}

Hi @ariopolis

It appears that in the latest version, the Swift compiler is confused by the chained nil coalescing (??) syntax. If you wrap the first ?? in parentheses, it will work fine:

func print<T: CustomStringConvertible>(label: String, event: Event<T>) {
  print(label, (event.element ?? event.error) ?? event)
}
2 Likes

Thank you @williammr and @scotteg, both suggestions worked.

I tried wrapping the second pair of elements, event.error and event in parenthesis, but that didn’t work for me. Wrapping the first two did which seems weird to me.

Wrapping the first pair of terms in parens seems to be a bit more succinct, so I will probably go with that.

Again, thank you!

This topic was automatically closed after 166 days. New replies are no longer allowed.