参数甚至未使用的通用T.Type和逗号分隔约束

时间:2016-12-27 05:23:29

标签: swift generics swift3

关于此代码的三个问题:

func register<T: UICollectionViewCell where T: ReusableView, T: NibLoadableView>(_: T.Type) {
    let bundle = NSBundle(forClass: T.self)
    let nib = UINib(nibName: T.nibName, bundle: bundle)

    registerNib(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
  1. (_: T.Type)。此func中的代码块甚至不使用此参数。那么为什么T.Type甚至是必要的,以及它如何将.Type添加到通用中呢?

  2. 这一行T: UICollectionViewCell where T: ReusableView, T: NibLoadableView,是否意味着:

    (a)T被约束为符合ReusableView NibLoadableView协议的UICollectionViewCell类型?

    (b)或者它是否意味着它符合ReusableView NibLoadableView?

  3. 第三个问题来自上面的例子,但它没有直接关系。我可以理解一个受限于特定类型的泛型;但是当泛型被约束为一种类型时,我不会看到它与输入变量的普通类型声明之间的区别。请参阅以下代码

  4. 这有什么区别:

    func register<T: UICollectionViewCell>(whatever: T) {
      // whatever
    }
    

    和此:

    func register(whatever: UICollectionViewCell) {
      // whatever
    }
    

    请勿同时上述两个声明声称register只期望某种类型限制为UICollectionViewCell?他们在不同的情况下或在何种情况下有所不同?

    (上下文示例代码摘自:https://gist.github.com/gonzalezreal/92507b53d2b1e267d49a

1 个答案:

答案 0 :(得分:3)

  1. 这意味着该参数是元类型。该参数被赋予类型(元类型),而不是该类型的实例。这是一个例子:

    func f<T>(_: T.Type) {
        print(T.self) //Prints "String"
    }
    
    f(String.self) // A metatype, not an instance of String
    
  2. 表示

  3. 就其本身而言,没有什么区别。第一个例子是使用泛型,第二个例子是使用多态。这是一个不同的例子:

    protocol Repairable {
        var broken: Bool { get set}
    }
    
    class Vehicle: Repairable {
        var broken = true
    }
    
    class CheapRepairableTrinket: Repairable {
        var broken = true
    }
    
    func repair<T: Repairable>(_ object: T) -> T {
        var object = object
        object.broken = false
    
        // The return type *must* be the same as the type of the parameter
        return object
    }
    
    func scamRepair(_ object: Repairable) -> Repairable {
        // the parameter type and the return type can be any Repairable
        // type, but there's no enforced relationship between them
        return CheapRepairableTrinket()
    }
    
    // I gave them a car to fix, and they gave me back some other crap!
    print(type(of: scamRepair(Vehicle())))