gpt4 book ai didi

swift - 如何减少 if-condition 循环 - Swift

转载 作者:行者123 更新时间:2023-11-28 06:01:56 25 4
gpt4 key购买 nike

我知道这听起来很疯狂,但我很好奇如何减少后续的 if 循环迭代?我试过使用 guard let 但卡在了某个地方。

{
if arenaEventItems == nil || arenaEventItems.count <= 0 {
return
}
if (arenaEventItems.count > 0 && (self.arenaEvents?.monthsDictObjList.count)! > 0){
if (self.tableView != nil){
if let arrVisibleRows = self.tableView.indexPathsForVisibleRows as? [IndexPath]{
if (self.tableView.indexPathsForVisibleRows!.count > 0){
let indexPath : IndexPath = self.tableView.indexPathsForVisibleRows!.first!
if let dict = self.arenaEvents?.monthsDictObjList[indexPath.row] {
if(self.arenaHeaderView != nil) && (dict.count) > 0 {
self.arenaHeaderView?.setMonthTitle(string: (dict.keys.first!))
let selectedMonthTitle = (dict.keys.first!)

for month in (self.arenaEvents?.uniqueMonthOnlyList)! {
if (selectedMonthTitle.contains(month)){
selectedMonthIndex = (self.arenaEvents?.uniqueMonthOnlyList.index(of: month)!)!
break
}
}
}
}
}
}
}
}
}

最佳答案

您可以像这样减少它,而无需任何强制解包或嵌套:

guard let arenaEventItems = arenaEventItems,
!arenaEventItems.isEmpty,
let arenaEvents = self.arenaEvents,
!arenaEvents.monthsDictObjList.isEmpty,
let arenaHeaderView = self.arenaHeaderView,
let indexPath = self.tableView?.indexPathsForVisibleRows?.first,
let selectedMonthTitle = arenaEvents.monthsDictObjList[indexPath.row].keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
if let monthIndex = arenaEvents.uniqueMonthOnlyList.index(where: { selectedMonthTitle.contains($0) }) {
selectedMonthIndex = monthIndex
}
  • if ... return 替换为 guard !... else return 以避免嵌套
  • .count > 0 替换为 !...isEmpty 作为最佳实践
  • 您将对 self.something? 的多次访问替换为 if let something = self.something 以避免线程问题
  • 你将 for ... in ... { if (...) { ... } } 解环到 .index(where: ...)

关于swift - 如何减少 if-condition 循环 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49377790/

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