gpt4 book ai didi

swift - 是否可以在 switch 运算符中解构对象?

转载 作者:可可西里 更新时间:2023-11-01 00:21:03 27 4
gpt4 key购买 nike

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

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
}

最佳答案

是的,这完全有可能。Swift 很强​​大 ;)

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

关于swift - 是否可以在 switch 运算符中解构对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44191041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com