Based on the reference for RxSwift BehaviorSubject
, the init(value:)
initializer is declared as
public init(value: Element)
Where the value
parameter is described as:
value
Initial value sent to observers when no other value has been received
by the subject yet.
And where Element
is the placeholder type of BehaviorSubject
:
public final class BehaviorSubject<Element> ...
This means you need to specify the placeholder type Element
as an Optional
type if you are to be able to set the initial value (used when no other value has been received) to nil
. E.g.:
class MyService {
let mySubject = BehaviorSubject<MyData?>(value: nil)
//....
}
Or, letting the compiler infer the placeholder as MyData?
by using the non-sugared .none
form for the nil
argument:
class MyService {
let mySubject = BehaviorSubject(value: Optional<MyData>.none)
//....
}
As for understanding the actual error message better, consider the following self-contained example:
struct Foo<T> {
init(value: T) {}
}
struct Bar {}
let bar = Bar()
_ = Foo<Bar>(value: bar) // OK
_ = Foo(value: bar) // OK, T inferred as Bar
_ = Foo<Bar>(value: nil) // Error: error: 'nil' requires a contextual type
_ = Foo<Bar?>(value: nil) // OK
_ = Foo(value: Optional<Bar>.none) // OK, T inferred as Bar?
BehaviorSubject
declaration?