Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 是否可以在switch operator中分解对象?_Swift_Pattern Matching - Fatal编程技术网

Swift 是否可以在switch operator中分解对象?

Swift 是否可以在switch operator中分解对象?,swift,pattern-matching,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.destin

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

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 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
对象中提取
identifier
destination
属性,如下面的伪代码:

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

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


我认为目前不可能在给定的模式中直接提取属性值–您可以始终切换
(segue.identifier,segue.destination)
switch (segue.identifier, segue.destination) {
    case let ("mocks"?, mocksController as MocksController):
             // do corresponding stuff here
  ...
}