News for hackers. Stuff that matters.
Re:Smashing Swift by afthonos on Sunday June 15, 2014 @04:43PM (#7896250)
That doesn't actually work, because you're limiting the return type of the method in the implementation of the functor. So by implementing that protocol, you could have one mapping from Int to String (say), but not another from Int to Double.

Put another way, you need to specify FunctorResult at implementation time, and the whole point is to only have to specify it at call time.

Re:Smashing Swift by jmah on Monday June 16, 2014 @12:19PM (#7899816)
This code works:

    let d = [1: 1, 2: 2, 3: 3]
    let intToInt = d.map { $0 + 1 }
    var IntToString = d.map { String($0) }
Re:Smashing Swift by afthonos on Thursday June 26, 2014 @10:06PM (#7952453)
The code works, but the type of the generic is not guaranteed at compile time. FunctorResult could be anything at all. There is no compile-time obligation for the code to return a Dictionary<KeyType, P>.

The more canonical example of a Functor is really the Optional. The mapping method for an optional looks like this:

  func fmap(f: A -> B) -> Optional<B> {
    switch self {
    case Some(let a):
      return Some(f(A))
    case None:
      return None
    }
  }
However, with your protocol, I can define the mapping function for the Optional as:

  func fmap(f: A -> B) -> B[] {
    switch self {
    case Some(let a):
      return [f(A)]
    case None:
      return B[]()
    }
  }
This would pass the type-checker, but is not what a Functor does.