gpt4 book ai didi

ios - 使用函数式 Swift 搜索 UIView 层次结构

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:51 25 4
gpt4 key购买 nike

我编写了一个函数,它循环访问给定 UIView 的 super View ,以获取对特定 UIView 子类(如果存在)的引用(在本例中为 UITableView)。这在使用命令式风格时效果很好,但它似乎确实是一个非常适合“面向铁路的编程”的问题。由于我仍在思考功能性问题,有谁能建议该功能的更优雅的功能性版本吗?

func findTableView(var view: UIView) -> UITableView? {
var table: UITableView? = nil
while table == nil {
guard let superView = view.superview else { return nil }
view = superView
table = view as? UITableView
}
return table
}

最佳答案

像这样?

func findTableView(view: UIView) -> UITableView? {
return view as? UITableView ?? view.superview.flatMap(findTableView)
}

此代码只是以下内容的快捷方式:

func findTableView(view: UIView) -> UITableView? {
if let tableView = view as? UITableView {
return tableView
}
else {
let superview = view.superview
if superview == nil {
return nil
}
else {
return findTableView(superview!)
}
}
}

使用 "Nil Coalescing Operator"flatMap(_:) 可选 枚举上的方法。

关于ios - 使用函数式 Swift 搜索 UIView 层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32969060/

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