草庐IT

swift - 为什么是 'there cannot be more than one conformance, even with different conditional bounds' ?

coder 2023-09-07 原文

我希望 Swift 让我能够在 where block 中为具有指定条件的类型创建扩展。我想象我可以根据具体泛型类型值 (T) 使用不同的扩展来扩展相同的泛型类型。但不是。以下示例演示了我的问题:

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

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

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

extension E: P where T.Prop == String {
   var property: String {
      switch 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 "Hello" 
    }
}

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

以下错误和注释是编译的结果。

error: conflicting conformance of 'E' to protocol 'P'; there cannot be more than one conformance, even with different conditional bounds extension E: P where T.Prop == String {

note: 'E' declares conformance to protocol 'P' here extension E: P where T.Prop == Int {

真的不可能吗?为什么?我如何使用我的代码才能成功?


在我的真实情况下展示问题的一些细节。
我有一些通用枚举,用于许多不同的包装类型。

enum Color<T> {
  case red(T), green(T)

  func map<T2>(_ transform: (T) -> T2) -> Color<T2> {
    switch self {
    case .red(let o): return .red(transform(o))
    case .green(let o): return .green(transform(o))
    }
  }
}

很多时候,我需要 Color 的不同扩展以使其符合不同的协议(protocol),具体取决于包装类型。有时这些协议(protocol)具有相同的基础( super )协议(protocol),因此,我遇到了当前的问题。有时我无法扩展 Color 以符合所有派生协议(protocol)的基本( super )协议(protocol),因为我需要不同的实现。

最佳答案

如前所述,您不能只进行这种扩展。但是,您可以像这样使用 hack:

protocol SomeExtension {
    func doSomething()
}

extension SomeExtension {
    func doSomething() {
        print("Do nothing or error")
    }
}

extension SomeExtension where Self == [String] {
    func doSomething() {
        print("String")
    }
}

extension SomeExtension where Self == [Int] {
    func doSomething() {
        print("Int")
    }
}

extension Array: SomeExtension { }

let stringsArr = ["a", "b", "d"]
let numbersArr = [1, 2, 3]
stringsArr.doSomething()
numbersArr.doSomething()

在控制台中可以看到

String
Int

关于swift - 为什么是 'there cannot be more than one conformance, even with different conditional bounds' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57282655/

有关swift - 为什么是 'there cannot be more than one conformance, even with different conditional bounds' ?的更多相关文章

随机推荐