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
...
}