2017-05-25 77 views
2

今天,我發現了一個笨拙的一段代碼:是否可以在開關操作員中解構對象?

if segue.identifier == "settings" { 
    if let settingsController = segue.destination as? SettingsController 
    { 
    //...setup settings controller here 
    } 
} else if segue.identifier == "mocks" { 
    if let mocksController = segue.destination as? MocksController 
    { 
    //...setup mocks controller here controller here 
    } 
} 
//... and a lot of if-elses 

我真的很討厭在我的代碼if-else-if,並決定重構這塊與switch。不幸的是我的快捷圖案匹配的知識是非常有限的,所以我能做的最好的是:

switch segue.identifier! { 
    case "mocks" where segue.destination is MocksController: 
    let mocksController = segue.destination as! MocksController 
    // do corresponding staff here 
    break 

    case "settings" where segue.destination is SettingsController: 
    let settingsController = segue.destination as! SettingsController 
    // do corresponding staff here 
    break 
} 

我想知道是否有可能從segue對象使用模式匹配如同僞提取identifierdestination性質代碼如下:

switch segue { 
    case let destination, let identifier where destination is ... && identifier == "...": 
    //do somthing 
    break 
} 
+1

我不相信這是目前可以直接提取給定模式的屬性值 - 你總是可以只切換'(segue.identifier,segue.destination)'雖然。 – Hamish

回答

5

是的,這是完全可能的。 斯威夫特是強大的;)

switch (segue.identifier, segue.destination) { 
    case let ("mocks"?, mocksController as MocksController): 
      // do corresponding stuff here 
    ... 
} 
相關問題