Hacker News new | ask | show | jobs
by anorwell 4334 days ago
You don't touch on the fact that options act can act Monads (i.e., that you can invoke an operation on the inner value, conditional on whether or not the optional value is present). For example, an optional user translates naturally to an optional user.name.

I haven't tried swift, and it's not obvious to me from the swift documentation if their options support arbitrary transformations, or just method chaining. In ruby (with ActiveSupport) this is the difference between:

      might_be_nil.try(:method)
and

      might_be_nil.try { |value| my_function(value) }
The latter is more general and useful than the former.
2 comments

Here's the source of try from active_support

    def try(*a, &b)
      if a.empty? && block_given?
        yield self
      else
        public_send(*a, &b) if respond_to?(a.first)
      end
    end
https://github.com/rails/rails/blob/d68419a88e424e588c2d8dec...

Should be easy to do the same in swift. Let me take a stab at it.

Here's an implementation of the latter try operator in swift.

    extension Optional {
        func try<U>(f: (T) -> U) -> Optional<U> {
            if let unwrapped = self {
                return f(unwrapped)
            } else {
                return nil
            }
        }
    }
You can see how to use it in this gist:

https://gist.github.com/nottombrown/c6585cad9588a9dc5383