Why does Combine assign crash when writing to an optional property?

This code crashes ("Unexpectedly found nil while unwrapping an Optional value")

Code Block
import Combine
class Receiver {
var value: Int!
var cancellables = Set<AnyCancellable>([])
init(_ p: AnyPublisher<Int,Never>) {
p.assign(to: \.value, on: self).store(in: &cancellables)
}
}
let receiver = Receiver(Just(5).eraseToAnyPublisher())


It does not crash if I use
Code Block
p.sink { self.value = $0 }.store(in: &cancellables)
instead of the assign, and it does not crash if I do not use an optional for the value-property.

To me this looks like a bug in Swift's constructor code, but maybe I am overlooking something?
Post not yet marked as solved Up vote post of kristofv Down vote post of kristofv
1.1k views

Replies

I believe it is because you are using an implicitly unwrapped optional value with Int!, which means that you are guaranteeing it will have a value before value is accessed.

To prevent the crash you should just assign an initial value to it.

var value: Int! = 0

That may or may not work for your situation.