3 ms·
This code works: let d = [1: 1, 2: 2, 3: 3] let intToInt = d.map { $0 + 1 } var IntToString = d.map { String($0) }
by jmah 12y ago
This code works:
let d = [1: 1, 2: 2, 3: 3]
let intToInt = d.map { $0 + 1 }
var IntToString = d.map { String($0) }
- afthonos 12y agoThe 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.