# Ignore nil values and unwrap optionals returning the value as the wrapped type

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! }
}

• It turns out it is feasible but requires extending the Optional enum. I am not sure if that is a good idea either. – nacross Jan 3 '16 at 9:59

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.

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

 .skipNil()

• 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. – nacross Sep 15 '17 at 0:33