今天我发现了一段笨拙的代码:
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
对象中提取destination
和segue
属性,如下面的伪代码所示:
switch segue {
case let destination, let identifier where destination is ... && identifier == "...":
//do somthing
break
}
答案 0 :(得分:6)
是的,它完全有可能。 斯威夫特是强大的;)
switch (segue.identifier, segue.destination) {
case let ("mocks"?, mocksController as MocksController):
// do corresponding stuff here
...
}