2014-10-04 44 views
3

我從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的使用’。

如何讓它工作?

回答

9

您的代碼有3個問題。

第一個是selectedPhoto被聲明爲可選的,因此在使用switch語句之前必須打開它 - 例如使用可選綁定。

第二個問題是您使用的語法不正確。在每個case必須指定的全名(包括類型),其次是一個冒號:

case BBPhoto1.kommunen: 
    // statements 

但由於類型可以通過在開關中使用的變量類型來推斷,則可以忽略該枚舉類型,但不點:

case .kommunen: 
    // statements 

最後,在一個迅速陳述switch要求所有案件(在你的案件3)明確地處理或使用default情況下覆蓋非在switch明確處理的所有案件。

你的代碼的工作版本會是什麼樣子:

enum BBPhoto1: Int { 
    case kommunen = 10 
    case sagsbehandler = 20 
    case festen = 30 
} 

var selectedPhoto: BBPhoto1? 

if let selectedPhoto = selectedPhoto { 
    switch (selectedPhoto) { 
    case .kommunen: 
     println(selectedPhoto.toRaw()) 

    case .sagsbehandler: 
     println(selectedPhoto.toRaw()) 

    default: 
     println("none") 
    } 
} 

需要注意的是,不同於其他語言,每種情況下的代碼不會自動下通到了下情況,所以break說法是不要求 - 唯一的用例是當案件沒有陳述時(沒有陳述的案例在swift中是錯誤的),在這種情況下,break只是作爲佔位符,其含義是「無所作爲」。

推薦閱讀:Conditional Statements

+0

嗯,不知道我理解爲什麼富人是在一個if語句... ,但我很欣賞的答案,並會接受它 – KennyVB 2014-10-04 08:14:49

+1

調用'fromRaw'返回一個可選的值,因爲你傳遞的原始價值可能不是一個有效的價值。那樣的話,你會收到'nil'。這就是爲什麼你必須聲明'selectedPhoto'是可選的。要使用'switch'中的值,你必須打開可選值。在這裏,@Antonio使用了可選的綁定語法'if let'。如果它不是'nil',則將非可選值綁定到變量。如果你向'fromRaw'傳遞了一個錯誤的值,並且你的'selectedValue'爲零,那麼'if let'後面的塊將不會被輸入。 – vacawama 2014-10-04 08:58:18

+0

謝謝@vacawama以這樣一種清晰的方式解釋:) – Antonio 2014-10-04 10:09:27