文章围绕这五点:
1. 泛型是什么
2. 为什么要用泛型
3. 泛型怎么用
4. 泛型进阶
5. 泛型的延伸使用
泛型(Generics)是什么?
引用Apple中Generics的描述:
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it. For example, Swift’s Array and Dictionary types are both generic collections. You can create an array that holds Int values, or an array that holds String values, or indeed an array for any other type that can be created in Swift. Similarly, you can create a dictionary to store values of any specified type, and there are no limitations on what that type can be.
大意是讲:
泛型可以让你使用定义的类型来编写灵活的、可重用的函数和类型,可以避免重复,以清晰,抽象的方式表达其意图。用人话来说(????),泛型给予我们更抽象的封装函数或类的能力,不严谨的来讲,一门语言越抽象使用越方便。Swift中的Array和Dictionary都是基于泛型编写的集合类型,如果不太理解也没关系,下面讲几个例子理解下。
1. Objective-C中的泛型
在2015年WWDC上苹果推出了Swift 2.0版本,为了让开发者从Objective-C更好得过渡到Swift上,苹果也为Objective-C带来了Generics泛型支持
Generics. Allow you to specify type information for collection classes like NSArray, NSSet, and NSDictionary. The type information improves Swift access when you bridge from Objective-C and simplifies the code you have to write.
所以我们经常看到的OC中的泛型比如:
1
2
3
4 // 实例化一个元素类型为`NSString`的数组
NSArray 《nsstring *》 *array = [NSArray new ];
// 或者字典
NSDictionary 《nsstring *, nsnumber *》 *dict = @{@ “manoboo” : @1}《/nsstring *, nsnumber *》《/nsstring *》
或者:
1
2 - (void)touchesBegan:(NSSet《uitouch *》 *)touches withEvent:(UIEvent *)event {
}《/uitouch *》
我们先看看OC中的泛型大概做了些什么:
打开NSArray.h 我们可以看到:
1
2
3
4
5
6
7 @interface NSArray《__covariant ObjectType》 : NSObject 《nscopying, nsmutablecopying, nssecurecoding, nsfastenumeration》
@property (readonly) NSUInteger count;
- (ObjectType)objectAtIndex:(NSUInteger)index;
- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithObjects:(const ObjectType _Nonnull [_Nullable])objects count:(NSUInteger)cnt NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
@end《/nscopying, nsmutablecopying, nssecurecoding, nsfastenumeration》
声明一个Generics的格式如下:
1
2 @interface 类名 《占位类型名称》
@end
占位类型后也可以加入类型限制,比如:
1
2 @interface MBCollection 《t: nsstring *》
@end《/t: nsstring *》
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
全部0条评论
快来发表一下你的评论吧 !