代码之家  ›  专栏  ›  技术社区  ›  Muhammad Aamir Ali

协议关联类型和

  •  2
  • Muhammad Aamir Ali  · 技术社区  · 7 年前

    protocol Repository {
        associatedtype T
        func add(data : T) -> Bool
    }
    

    protocol Repository {
        func add<T>(data : T) -> Bool
    }
    
    3 回复  |  直到 7 年前
        1
  •  6
  •   Taras Chernyshenko    7 年前

    定义的关联类型使符合协议的类成为强类型。这提供了编译时错误处理。

    另一方面,泛型类型使符合协议的类更加灵活。

    protocol AssociatedRepository {
        associatedtype T
        func add(data : T) -> Bool
    }
    
    protocol GenericRepository {
        func add<T>(data : T) -> Bool
    }
    
    
    class A: GenericRepository {
        func add<T>(data : T) -> Bool {
            return true
        }
    }
    
    class B: AssociatedRepository {
        typealias T = UIViewController
        func add(data : T) -> Bool {
            return true
        }
    }
    

    A 能把任何一门课放到 add(data:) 函数,所以需要确保函数处理所有情况。

    A().add(data: UIView())
    A().add(data: UIViewController())
    

    两者都是有效的

    但是为了上课 B UIViewController

    B().add(data: UIView()) // compile-time error here
    B().add(data: UIViewController())
    
        2
  •  4
  •   vadian    7 年前
    • associatedtype 是struct/class中的静态类型,通过 typealias

    • 泛型可以是任何类型,甚至是同一类中的不同类型。

        3
  •  3
  •   fewlinesofcode user10694837    7 年前

    这个案子

    protocol Repository {
        func add<T>(data : T) -> Bool
    }
    

    func add Bool "

    但是这个

    protocol Repository {
        associatedtype T
        func add(data : T) -> Bool
    }
    

    函数添加 typealias T = ... 布尔 "

    在第二种情况下,您仅将泛型参数限制为typealiased类型。

    func add<T> func multiply<T> T . 如果是泛型函数,则不能保证。

    protocol Calculable {
        associatedtype T
        func add<T>(a: T, b: T) -> T
        func multiply<T>(a: T, b: T) -> T
    }
    // In this case you know that T is the same for all functions
    
    protocol CalculableDifferent {
        func add<T>(a: T, b: T) -> T
        func multiply<T>(a: T, b: T) -> T
    }
    // In this case add can accept One type, when multiply can accept Another