'Generic methods evaluation type - Swift

Below is the playground code snippet

import UIKit

class BaseCell: UICollectionViewCell {
    
}

class SubCell: BaseCell {
    
}

var type: BaseCell.Type = SubCell.self


extension UICollectionViewCell {
    @objc public class var reuseIdentifier: String {
        return String(describing: self)
    }
}

func registerNib<T: UICollectionViewCell>(_: T.Type) -> String {
    return T.reuseIdentifier
}

print(type.reuseIdentifier) // prints "SubCell"

print(registerNib(type)) // prints "BaseCell" **how?**

When I'm using the generic function here the output changes, why? Anything im doing wrong here?



Solution 1:[1]

Generics are evaluated at compile-time, not runtime. The type of type is BaseCell.Type, so that's what will be used for the call to registerNib. Its value is not relevant, just its type.

You didn't mean a generic here. You meant to pass the type value so it could be evaluated at runtime:

func registerNib(_ type: UICollectionViewCell.Type) -> String {
    type.reuseIdentifier
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1