是否可以在开关操作器中对对象进行解构?

时间:2017-05-25 22:59:00

标签: swift pattern-matching

今天我发现了一段笨拙的代码:

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
}

我想知道是否可以使用模式匹配从identifier对象中提取destinationsegue属性,如下面的伪代码所示:

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

1 个答案:

答案 0 :(得分:6)

是的,它完全有可能。 斯威夫特是强大的;)

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