简体   繁体   中英

Implementation of Functor protocol with associated type (Swift)

I'm trying to implement a Functor in Swift myself and found that I cant specify different associated type for return type of generic map function. Please give suggestions where I'm wrong.

This is my code:

protocol Functor {
 associatedtype T

 func map<U>(_ transform: (T) -> U) -> Self // should return `Self` with associated type U
}

enum Result<A>: Functor {
 typealias T = A

 case success(A)
 case failure(Error)

 func map<U>(_ transform: (A) -> U) -> Result<A> { // autocompletion sets return type as `Result<A>` instead of Result<U>
  switch self {
  case let .success(value):
   return .success(transform(value))
  default:
   return self
  }
 }
}

As you intend to change the associated type of your Functor by applying map , the return type cannot be Self in your protocol definition. This could be solved by having the return type be another associated type that is also a Functor (and which can be Self by default) that is free to choose the type is it going to be generic over. Something like this:

protocol Functor {
    associatedtype A
    associatedtype B: Functor = Self

    func map<C>(_ transform: (A) -> C) -> B where B.A == C
}

enum Result<Value>: Functor {
    typealias A = Value

    case success(Value)
    case failure(Error)

    func map<C>(_ transform: (A) -> C) -> Result<C> {
        switch self {
        case let .success(value): return .success(transform(value))
        case let .failure(error): return .failure(error)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM