代码之家  ›  专栏  ›  技术社区  ›  BenJacob Petr

符合Swift中关联类型协议的异构数组

  •  0
  • BenJacob Petr  · 技术社区  · 5 年前

    AProtocol 具有关联类型 AType 还有一个函数 aFunc . 我想延长 Array 通过使用其元素的结果使其符合协议 aFunc公司 Aprotocol 并且具有相同的关联类型,所以我设置了这个玩具示例:

    protocol AProtocol {
        associatedtype AType
        func aFunc(parameter:AType) -> Bool
    }
    
    extension Array : AProtocol where Element : AProtocol, Element.AType == Int {
        func aFunc(parameter: Int) -> Bool {
            return self.reduce(true, { r,e in r || e.aFunc(parameter: parameter) })
        }
    }
    
    extension String : AProtocol {
        func aFunc(parameter: Int) -> Bool {
            return true
        }
    }
    
    extension Int : AProtocol {
        func aFunc(parameter: Int) -> Bool {
            return false
        }
    }
    

    对于仅包含一种类型的数组,此操作很有效:

    let array1 = [1,2,4]
    array1.aFunc(parameter: 3)
    

    但是对于异构阵列,我得到了错误 Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional 然后 Value of type '[Any]' has no member 'aFunc' 如果注释如下:

    let array2 = [1,2,"Hi"] as [Any]
    array2.aFunc(parameter: 3)
    

    是否可以按照我的意愿扩展数组,以便允许异类数组,只要它们符合 阿普洛托科尔 有同样的东西 A型

    0 回复  |  直到 5 年前
        1
  •  1
  •   user1046037    5 年前

    看看这是否符合你的需要。

    方法:

    实施:

    protocol BProtocol {
        func aFunc(parameter: BProtocol) -> Bool
    }
    
    extension String : BProtocol {
        func aFunc(parameter: BProtocol) -> Bool {
            return true
        }
    }
    
    extension Int : BProtocol {
        func aFunc(parameter: BProtocol) -> Bool {
            return false
        }
    }
    
    extension Array : BProtocol where Element == BProtocol {
    
        func aFunc(parameter: BProtocol) -> Bool {
            return self.reduce(true, { r,e in r || e.aFunc(parameter: parameter) })
        }
    }
    

    调用:

    let a1 : [BProtocol] = [1, 2, 3, "Hi"]
    
    let boolean = a1.aFunc(parameter: 1)