swift和oc枚举的区别

返回上级目录:swift,oc语法(苹果文档)和对比

OC

1.oc的枚举值相当于这个文件中的一个局部变量,只能是整型

2.不同枚举中,枚举名称不可以一样,在同一文件

实例代码

#import "ViewController.h"

enum Week {
    
    
    one = 100, two, three = 500, four
};


@interface ViewController ()

@property(nonatomic,assign) enum Week week;

@end

@implementation ViewController

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    UIView *view = [UIView new];
    self.week = two;
    switch (self.week) {
    
    
        case one:
            NSLog(@"%d",one);
            break;
        default:
            NSLog(@"%d",four);
            break;
    }
    // Do any additional setup after loading the view.
}

@end

参考博客:
iOS(三)OC中的枚举(NS_ENUM和NS_OPTION)

swift

3.枚举里可以写方法

4.枚举的rawValue可以是Float(float也是赋值的后面依次+1)或是String,或是没有

enum Suit{
    
    
    case spades, hearts, diamonds, clubs

    func simpleDescription() -> String {
    
    
        switch self {
    
    
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }

    func color() -> String {
    
    
        switch self {
    
    
        case .spades, .clubs:
            return "black"
        default:
            return "red"
        }
    }
}

5.可以用Rank(rawValue: 3)方法创建一个枚举实例

if let convertedRank = Rank(rawValue: 3) {
    
    
    let threeDescription = convertedRank.simpleDescription()
}

5.枚举实例可以带参数

enum ServerResponse {
    
    
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

switch success {
    
    
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
}
// Prints "Sunrise is at 6:00 am and sunset is at 8:09 pm."

猜你喜欢

转载自blog.csdn.net/baidu_40537062/article/details/109072350