[swift-users] Generics question - can you handle both optional and non-optional args with the same function?

Charles Srstka cocoadev at charlessoft.com
Thu Jan 11 20:27:09 CST 2018

> On Jan 11, 2018, at 7:55 PM, Kenny Leung via swift-users <swift-users at swift.org> wrote:
> I’m trying to write a utility method that is kind of the opposite of “x ?? y”, which means “x != nil ?  x : y”. I want “x != nil ? f(x) : nil”

A good name for this method might be ‘map’ ;-)

> This is not difficult to write, but if you have "f(x)->z" and "g(x)->z?",

And a good name for this one might be ‘flatMap’. ;-)

> I seem to need two versions of the function in order to handle it. Is there any way to do this with only one function?

I don’t think so; if this were possible, there probably wouldn’t be the two methods to do this in the standard library.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20180111/5a3aa361/attachment.html>

More information about the swift-users mailing list