我從ObjC得到了這段代碼。我想將其轉換爲斯威夫特,但是,我有這樣的困難......如何使枚舉開關case(swift)
ObjC代碼:
navgivet.h
typedef NS_ENUM(NSInteger, BB3Photo) {
kirkenType = 10 ,
festenType = 20 ,
praestType = 30
};
@property (nonatomic, assign) BB3Photo selectedPhotoType;
navgivet.m
- (IBAction)changeImage:(id)sender {
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *button = sender;
_selectedPhotoType = button.tag;
}
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Vælg Billed"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:@"Vælg fra Biblioteket", @"Vælg Kamera", nil];
sheet.actionSheetStyle = UIActionSheetStyleDefault;
[sheet showInView:[self.view window]];
}
switch (_selectedPhotoType) {
case kirkenType: {
}break;
case festenType: {
}break;
case praestType: {
}break;
default:
break;
這裏是我的SWIFT代碼在此嘗試
enum BBPhoto1: Int {
case kommunen = 10
case sagsbehandler = 20
case festen = 30
}
@IBAction func changeImage(sender: AnyObject){
if sender .isKindOfClass(UIButton){
let button: UIButton = sender as UIButton
selectedPhoto = BBPhoto1.fromRaw(button.tag)
}
let actionSheet = UIActionSheet(title: "Billeder", delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: nil, otherButtonTitles: "Vælg fra Biblioteket", "Vælg Kamera")
actionSheet.showInView(self.view)
}
var selectedPhoto: BBPhoto1?
switch (selectedPhoto) {
case kommunen {
}
case sagsbehandler{
}
}
,但我得到的錯誤:與同messege但Sagsbehandler‘未解決的標識符kommunen的使用’。
如何讓它工作?
嗯,不知道我理解爲什麼富人是在一個if語句... ,但我很欣賞的答案,並會接受它 – KennyVB 2014-10-04 08:14:49
調用'fromRaw'返回一個可選的值,因爲你傳遞的原始價值可能不是一個有效的價值。那樣的話,你會收到'nil'。這就是爲什麼你必須聲明'selectedPhoto'是可選的。要使用'switch'中的值,你必須打開可選值。在這裏,@Antonio使用了可選的綁定語法'if let'。如果它不是'nil',則將非可選值綁定到變量。如果你向'fromRaw'傳遞了一個錯誤的值,並且你的'selectedValue'爲零,那麼'if let'後面的塊將不會被輸入。 – vacawama 2014-10-04 08:58:18
謝謝@vacawama以這樣一種清晰的方式解釋:) – Antonio 2014-10-04 10:09:27