iOS 一一 枚举类型

来源:互联网 发布:通信网络优化是什么 编辑:程序博客网 时间:2024/05/16 11:48

////  ViewController.m//  Enum////  Created by 朝阳 on 2017/12/15.//  Copyright © 2017年 sunny. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"%d,%d,%d,%d",Spring,Summer,Autumn,Winter);    enum Season season = Spring;    [self printSeason:season];        NSLog(@"---------");    Sex sex = MAN;    [self printSex:sex];        NSLog(@"---------");    [self printDirection:ZYTypeTop];        NSLog(@"---------");    [self demo:ZYActionTypeTop | ZYActionTypeRight];    }// 第一种: 普通枚举enum Season{    Spring = 0,    Summer = 1,    Autumn = 2,    Winter = 3};- (void)printSeason:(enum Season)season{    switch (season) {        case Spring:            printf("春! \n");            break;        case Summer:            printf("夏! \n");            break;        case Autumn:            printf("秋! \n");            break;        case Winter:            printf("冬! \n");            break;        default:            break;    }}// 第二种: 别名枚举typedef enum{    MAN,    WOMAN,    OTHER,}Sex;- (void)printSex:(Sex)sex{    switch (sex) {        case MAN:            printf("男! \n");            break;        case WOMAN:            printf("女! \n");            break;        case OTHER:            printf("不男不女! \n");            break;        default:            break;    }}// 第三种 typedf NS_ENUM 定义类型typedef NS_ENUM(NSInteger,ZYType){    ZYTypeTop,    ZYTypeRight,    ZYTypeBottom,    ZYTypeLeft};- (void)printDirection:(ZYType)direction{    switch (direction) {        case ZYTypeTop:            printf("上! \n");            break;        case ZYTypeRight:            printf("右! \n");            break;        case ZYTypeBottom:            printf("下! \n");            break;        case ZYTypeLeft:            printf("左! \n");            break;                    default:            break;    }}// 第四种 位移枚举// 一个参数可以传递多个值// 注意: 当遇到位移枚举时,观察第一个枚举值,如果 !=0, 直接传0做参数即可,性能最高typedef NS_OPTIONS(NSInteger, ZYActionType){    ZYActionTypeTop = 1<<0, // 1 * 2(0) = 1    ZYActionTypeRight = 1<<1, // 1 * 2(1) = 2    ZYActionTypeBottom = 1<<2, // 1 * 2(2) = 4    ZYActionTypeLeft = 1<<3, // 1 * 2(3) = 8};// 按位与 &  1&1==1  1&0==0  0&0==0; 只要有0则为0// 按位或 |  1|1==1  1|0==1  0|0==0; 只要有1则为1- (void)demo:(ZYActionType)type{    NSLog(@"type--%ld",type);        if (type & ZYActionTypeTop) {        NSLog(@"上---%ld",type & ZYActionTypeTop);    }    if (type & ZYActionTypeRight) {        NSLog(@"右---%ld",type & ZYActionTypeRight);    }    if (type & ZYActionTypeBottom) {        NSLog(@"下---%ld",type & ZYActionTypeBottom);    }    if (type & ZYActionTypeLeft) {        NSLog(@"左---%ld",type & ZYActionTypeLeft);    }}@end