Sunday, December 17, 2023
HomeiOS Developmentswift - Why 'there can't be a couple of conformance, even with...

swift – Why ‘there can’t be a couple of conformance, even with totally different conditional bounds’?


I hoped that Swift offers me the flexibility to create an extension for kind with specified situations in the place block. I imagined that I can prolong the identical generic kind with totally different extensions depending on concrete generic kind worth (T). However not. Following instance demonstrates my drawback:

protocol P {    
    associatedtype Prop 
    var property: Prop { get }
}

enum E<T: P> {
   case single(T)
   case double(T)
}

extension E: P the place T.Prop == Int {
   var property: Int {
      swap self {
      case .single(let o): return o.property
      case .double(let o): return o.property * 2
      }
   }
}

extension E: P the place T.Prop == String {
   var property: String {
      swap self {
      case .single(let o): return o.property
      case .double(let o): return o.property + o.property
      }
   }
}

struct Int4: P {
   var property: Int {
       return 4
   }
}

struct StringHello: P {
    var property: String {
        return "Hi there" 
    }
}

print(E.single(Int4()).property)
print(E.double(StringHello()).property)

Following error and notice are the results of the compilation.

error: conflicting conformance of ‘E’ to protocol ‘P’; there can’t be a couple of conformance, even with totally different conditional bounds
extension E: P the place T.Prop == String {

notice: ‘E’ declares conformance to protocol ‘P’ right here
extension E: P the place T.Prop == Int {

Is it actually unattainable? Why? What can I do with my code to succeed?


Some particulars to reveal the issue in my actual state of affairs.
I’ve some generic enum, which is used with many various wrapped sorts.

enum Coloration<T> {
  case pink(T), inexperienced(T)

  func map<T2>(_ remodel: (T) -> T2) -> Coloration<T2> {
    swap self {
    case .pink(let o): return .pink(remodel(o))
    case .inexperienced(let o): return .inexperienced(remodel(o))
    }
  }
}

Fairly often, I would like totally different extensions for Coloration to adapt it to totally different protocols relying on the wrapped kind. Generally these protocols have the identical base (tremendous) protocol and in consequence, I’ve the present drawback. Generally I cant prolong Coloration to adapt this base (tremendous) protocol for all deriving protocols as a result of I would like totally different implementations.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments