4 ms·
I'm not a huge fan of Optional.matching (also commonly called Optional.filter) because you may want to "filter" non-optionals as well, i.e. T -> Optional<T> giv
by timjver 8y ago
I'm not a huge fan of Optional.matching (also commonly called Optional.filter) because you may want to "filter" non-optionals as well, i.e. T -> Optional<T> given a predicate. Unfortunately Swift doesn't (yet?) allow writing extensions on any generic T and the alternatives are a free function and an Optional initialiser, neither of which allows you to easily chain them. (Another alternative is a custom operator, but let's not.)
So perhaps the best we can do is Optional.matching as defined in the post, combined with turning a non-optional into an optional using Optional(...) in case we want to "filter" non-optional values using a predicate.
- aaaaaaaaaab 8y agoUniform Call Syntax would solve this elegantly: https://en.m.wikipedia.org/wiki/Uniform_Function_Call_Syntax https://en.m.wikipedia.org/wiki/Uniform_Function_Call_Syntax
- aplummer 8y ago> Unfortunately Swift doesn't (yet?) allow writing extensions on any generic T I'm keen to understand the use case for this kind of code, where T literally conforms to zero protocols. Would you not create a protocol with a default implementation and then conform to that in this case? An example would help me a lot!
- iBelieve 8y agoThe way I do this in Rust is `Some(...).filter(...)`. I personally like this over having generic extensions, as it makes it very clear that its doing filtering that produces an optional, rather than filtering through a list or other iterable.