__kindof和__covariant

2,444 阅读1分钟

我们经常看到OC中的泛型是这样的:

// 实例化一个元素类型为`NSString`的数组
NSArray <NSString *> *array = [NSArray new];
// 或者字典
NSDictionary <NSString *, NSNumber *> *dict = @{@"manoboo": @1}

这里的类型都是写死的,我们可以使用__covariant,它可以使子类强转到父类型。 我们写泛型的类就可以这样写了:

@interface TYPagerViewLayout<__covariant ItemType> : NSObject

那么在使用的时候,这个泛型的类型就可以变:

@property (nonatomic, strong, readonly) TYPagerViewLayout<UIView *> *layout;

或者

@property (nonatomic, strong, readonly) TYPagerViewLayout<NSString *> *layout;

都是可以的。


有时候我们自定义一个View,里面有一个UICollectionView,这个时候我们允许自定义UICollectionViewCell,有方法:

- (__kindof UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;

这里使用__kindof,而不是id,可以避免传的不是UICollectionViewCell,明确了返回值是UICollectionViewCell或者UICollectionViewCell的子类,也不用强转。