swift和oc枚舉的區別

返回上級目錄:swift,oc語法(蘋果文檔)和對比

swift

OC

1.oc的枚舉值至關於這個文件中的一個局部變量,只能是整型

2.不一樣枚舉中,枚舉名稱不能夠同樣,在同一文件

實例代碼ui

#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)
atom

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.枚舉實例能夠帶參數spa

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."
相關文章
相關標籤/搜索