首先看到swift扩展的时候,我就想起了OC的扩展和类别;于是我就在找swift的扩展和OC的扩展和类别是什么关系。经过几番查阅资料,发现swift的扩展和OC的类别是如出一辙。但是我又很一根筋地去查找swift类似OC扩展的东西是什么。但是我始终就是没找到,于是我就静下来想想,OC的扩展和分类的作用和区别是什么?使用场景是什么?所以,我们首先来看看OC的类别和扩展:
类别:可以动态的为现有类添加新的方法
//接口文件
@interface 已有类(类别名)
//方法定义
@end
//实现部分
@implementation 已有类(类别名)
//方法实现
@end
eg:
#import <UIKit/UIKit.h>
@interface UIColor (UIColorUInt32)
+(UIColor *)colorWithHexString:(NSString *)valueStr;
@end
#import "UIColor+UIColorUInt32.h"
@implementation UIColor (UIColorUInt32)
+(UIColor *)colorWithHexString:(NSString *)valueStr{
NSScanner * scanner = [NSScanner scannerWithString:valueStr];
UInt32 hexStr = 0;
if (![scanner scanHexInt:&hexStr]) {
return [UIColor clearColor];
}else{