代码之家  ›  专栏  ›  技术社区  ›  Michel

一般函数参数的多重约束

  •  0
  • Michel  · 技术社区  · 7 年前

    阅读swift中的泛型函数,我发现通过要求参数是给定类C的子类,或者它实现给定协议P,可以对其施加一些约束。 但我想知道是否有办法同时要求两者。我还没有找到任何关于这个的信息。

    有人知道吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Prashant Tukadiya    7 年前

    实际上你可以做到。

    如果你看到 Codable 事实上,在斯威夫特 Decodable Encodable

     typealias Codable = Decodable & Encodable
    

    所以在某些函数中,如果使用泛型t作为可编码的

    struct StructOfCodable<T:Codable>: Codable {
         ....
    }
    

    下面是例子

    protocol Test {}
    class TClass {
    
    }
    
    typealias Common = Test & TClass
    
    func generic <T:Common>(method:T) {
    
    }
    

    另一种方法是协议和类都可以拥有超级类。这样您就可以创建公共协议

    喜欢

    protocol CommonInProtocolAndStruct { }
    
    protocol ProtocolUsedAsConstraint:CommonInProtocolAndStruct {} 
    
    struct StructUsedAsConstraint:CommonInProtocolAndStruct {} 
    

    任何你能用的方法 CommonInProtocolAndStruct 作为一般约束

        2
  •  1
  •   rob mayoff    7 年前

    可以使用 where 条款。实例:

    import UIKit
    
    func f<T>(t: T) where T: UIView, T: Encodable {}
    
    class C<T> where T: UIView, T: Encodable {}