2
\$\begingroup\$

My primary concern is that this has been written as a global function. I think it would be better if this was a function of the SignalProducer class but I am not sure that is even possible. Is this thinking justified or is the use of global functions acceptable?

(The following code uses ReactiveCocoa 4 and is written in Swift.)

func ignoreNilValues <Value,Error> (producer: SignalProducer<Value?,Error>) -> SignalProducer<Value, Error> {
    return producer.filter { return $0 != nil }.map { $0! }
}
\$\endgroup\$
  • \$\begingroup\$ It turns out it is feasible but requires extending the Optional enum. I am not sure if that is a good idea either. \$\endgroup\$ – nacross Jan 3 '16 at 9:59
1
\$\begingroup\$

After finding out that it was feasible I rewrote the global function as follows.

protocol AnOptional {
    typealias Wrapped
    func asOptional() -> Wrapped?
}

extension Optional : AnOptional {
    func asOptional() -> Wrapped? {
        return self
    }
}

extension SignalProducer where Value : AnOptional {
    func ignoreNilValues() -> SignalProducer<Value.Wrapped,Error> {
        return self.filter { return $0 != nil }.map { $0.asOptional()! }
    }
}

This is much cleaner in terms of usage but requires extending the Optional type which I am not sure would be considered best practice.

For the specific case of ignoring nil values sent from a signal it turns out there is a much simpler way, which unfortunately I missed until now.

let producer: SignalProducer<SomeValueType?,SomeErrorType>
let producerNoNil: SignalProducer<SomeValueType,SomeErrorType> = producer.ignoreNil()

Incidentally the implementation of ignoreNil seems to use the approach mentioned above.

\$\endgroup\$
1
\$\begingroup\$

There is already a function in reactiveSwift that you can use:

 .skipNil()
\$\endgroup\$
  • 1
    \$\begingroup\$ As mentioned in my original answer, I ended finding ignoreNil() but the question is looking for a general swift approach not only one specific reactivecocoa/swift. \$\endgroup\$ – nacross Sep 15 '17 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.