有时,我想guard与let&结合使用where来简化我的代码。但我想知道 let 的优先级是什么以及在哪里。例如:
class Person {
func check() -> Bool? {
print("checking")
return nil
}
}
func test(dont: Bool) {
let person = Person()
guard let check = person.check() where dont else {
print("should not check")
return
}
print("result: \(check)")
}
test(false)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的控制台结果,打印输出为:
let check = person.check() where dont对于in语法的条件guard <condition> else { },即使 in 中的表达式where与 in 中表达式的结果无关let,Swift 似乎也是let先执行后检查where。有时在我的代码中,let可选绑定需要大量计算,并且where …
我在导航项目上使用UISearchController(导航栏已设置为使用barTintColor和tintColor)。关闭搜索控制器后(点击搜索栏的“取消”按钮),后退按钮的tintColor将恢复为默认值(蓝色)。
屏幕截图2:当UISearchController处于活动状态时:

屏幕快照3:关闭UISearchController时(通过点击“取消”),您会看到“后退”按钮的tintColor恢复为默认值(蓝色),而不是白色:

屏幕截图上的代码是:
/// View controller is embedded in a UINavigationController, the root view controller of the startup storyboard.
class ViewController: UIViewController {
lazy var searchController: UISearchController = {
let controller = UISearchController(searchResultsController: nil)
controller.searchBar.tintColor = .white
return controller
}()
override func viewDidLoad() {
super.viewDidLoad()
if let navigationBar = navigationController?.navigationBar {
setupNavigationBar(navigationBar)
}
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
navigationItem.titleView = searchController.searchBar
}
}
func setupNavigationBar(
_ navigationBar: UINavigationBar,
barTintColor: UIColor = …Run Code Online (Sandbox Code Playgroud)