最近在github上看见一篇<<招聘一个靠谱的iOS>>,看了看里面的试题,都是些很基础又很底层的东西,当然现在还再学习中,能从微博@iOS程序犭袁 所提供的答案中学习到很多之前不知道的知识。现在才察觉到,原来自己的所需要学习的还有很多很多,和这些大牛相比,更是渣渣都不是啊!而且出这套题的”孙源” ,就职于百度,而且还是90后,想想自己一个80后,真的很差,好了,不多说这些,从现在努力向前就好了!
其中第一道题就是有枚举(ENUM)规范写法的问题,正巧今天又在枚举上碰上问题,所以就简单总结了下枚举相关的简单东西。
当然,下面的问题,我就只总结关于枚举。
修改完的代码:
修改方法有很多种,现给出一种做示例:
// .h文件
// 修改完的代码,这是第一种修改方法,后面会给出第二种修改方法
typedef NS_ENUM(NSInteger, CYLSex) {
CYLSexMan,
CYLSexWoman
};
@interface CYLUser : NSObject<NSCopying>
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, assign) NSUInteger age;
@property (nonatomic, readonly, assign) CYLSex sex;
- (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(CYLSex)sex;
+ (instancetype)userWithName:(NSString *)name age:(NSUInteger)age sex:(CYLSex)sex;
@end
enum建议使用 NS_ENUM
和 NS_OPTIONS
宏来定义枚举类型,参见官方的 Adopting Modern Objective-C 一文:
// 定义性别的枚举 这样可能就比较严谨
typedef NS_ENUM(NSInteger, CYLUserGender) {
CYLUserGenderUnknown,
CYLUserGenderMale,
CYLUserGenderFemale,
CYLUserGenderNeuter
};
提供问题答案大神微博 http://weibo.com/luohanchenyilong/
提供问题答案大神的github https://github.com/ChenYilong
- 常见枚举类型定义
typedef enum
{
East,
South,
West,
North
}Direction;
- 在iOS6和Mac OS 10.8以后Apple引入了两个宏来重新定义这两个枚举类型,实际上是将enum定义和typedef合二为一,并且采用不同的宏来从代码角度来区分。
- 从枚举定义来看,NS_ENUM和NS_OPTIONS本质是一样的,仅仅从字面上来区分其用途。NS_ENUM是通用情况,NS_OPTIONS一般用来定义具有位移操作或特点的情况(bitmask)。
typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
UIViewAnimationTransitionNone,//默认从0开始
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
};
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
这两个宏的定义在Foundation.framework的NSObjCRuntime.h中
#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum))
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#if (__cplusplus)
#define NS_OPTIONS(_type, _name) _type _name; enum : _type
#else
#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
#endif
#else
#define NS_ENUM(_type, _name) _type _name; enum
#define NS_OPTIONS(_type, _name) _type _name; enum
#endif
Swift中的枚举相对于C语言变化还是很大的
写到这里发觉自己的功底还是不行,然后又去看了大牛的几篇文章,感觉自己再怎么总结,也没有人家的深度与广度,还不如趁这个时间去多学习学习呢!
// Swift 中简单使用枚举
enum RequsetMethod: String {
case GET = "GET"
case POST = "POST"
}