gpt4 book ai didi

swift - 在 observeValueForKeyPath 中使用开关

转载 作者:搜寻专家 更新时间:2023-11-01 05:37:46 26 4
gpt4 key购买 nike

我试图通过用单个 switch 语句替换典型的长字符串嵌套 if/else 语句来提高我的 KVO observeValueForKeyPath 实现的易读性。

到目前为止,唯一真正起作用的是:

private let application = UIApplication.sharedApplication()

switch (object!, keyPath!) {

case let (object, "delegate") where object as? UIApplication === application:
appDelegate = application.delegate
break

...

default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}

如果有的话,它比以下内容更难阅读:

    if object as? UIApplication === application && keyPath! == "delegate" {

}
else {

}

有人有在observeValueForKeyPath(和类似方法)中使用 switch 的好模型吗

编辑:与下面@critik 的问题相关,这里有更多代码来演示仅使用 switch (object as! NSObject, keyPath!){ 的问题:

private let application = UIApplication.sharedApplication()
private var appDelegate : UIApplicationDelegate?
private var rootWindow : UIWindow?

public override func observeValueForKeyPath(
keyPath: String?,
ofObject object: AnyObject?,
change: [String : AnyObject]?,
context: UnsafeMutablePointer<Void>) {

switch (object as! NSObject, keyPath!) {
case (application, "delegate"):
appDelegate = application.delegate
(appDelegate as? NSObject)?.addObserver(self, forKeyPath: "window", options: [.Initial], context: nil)
break

case (appDelegate, "window"):
rootWindow = appDelegate?.window?.flatMap { $0 }
break

case (rootWindow, "rootViewController"):
rebuildViewControllerList(rootWindow?.rootViewController)
break

default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}

最佳答案

元组上的开关怎么样:

switch (object as! NSObject, keyPath!) {

case (application, "delegate"):
appDelegate = application.delegate

...

default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}

注意 1. 虽然我再次反对 Swift 中的强制转换(向下转换、解包等),但您可以安全地强制向下转换为 NSObject 而不会发生崩溃,因为每this SO question , KVO 仅适用于 NSObject 子类。

注意 2. 在 Swift 中您也不需要 break,这也会将您的代码至少缩短一行 :)

关于swift - 在 observeValueForKeyPath 中使用开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883367/

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