如何编写返回三种类型之一的 swift 函数?



我有三个视图控制器,WebkitViewController,然后是另外两个视图控制器WebkitViewControllerA,以及WebkitViewControllerB都扩展WebkitViewController。我在编写一个通用函数时遇到问题,该函数将查看 segue 目的地的视图控制器并告诉我它是三种类型中的哪一种。有没有更好的方法可以做到这一点?

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is WebKitViewController && sender is UIButton {
let viewControllerType = {
if segue.destination is WebKitViewControllerA {
WebKitViewControllerA.self
} else if segue.destination is WebKitViewControllerB {
WebKitViewControllerB.self
} else {
WebKitViewController.self
}
}()
let button = sender as? UIButton
let vc = segue.destination as? viewControllerType
vc?.foo = "ho ho ho"
}
}
}

我还尝试了如下方法:

var vc: WHAT_TYPE_TO_PUT_HERE?
if segue.destination is CustomViewController {
vc = segue.destination as? CustomViewController
} else if segue.destination is WebKitBelowFoldViewController {
vc = segue.destination as? WebKitBelowFoldViewController
} else {
vc = segue.destination as? WebKitViewController
}

但我不知道我可以给 vc 哪种类型,类型检查器会得到满足。

由于这些都是WebkitViewController的子类,因此vc是WebkitViewController。此外,鉴于您在此处显示的代码,应该没有理由检查每种类型。您应该要求的只是:

if let vc = segue.destination as? WebKitViewController {
vc.foo = "ho ho ho"
}

与其试图摆弄具体类型,不如创建一个所有三个 VC 都遵守的协议。

看起来这三个 VC 的共同点是它们都具有foo属性,因此我们可以创建如下协议:

protocol HasFoo { // you should give this a better name base on your actual situation
var foo: String! { get set } // remember to match the type of the foo property
}

然后让三个VC符合它:

extension WebKitViewController : HasFoo {
}
extension WebKitViewControllerA : HasFoo {
}
extension WebKitViewControllerB : HasFoo {
}

现在你可以简单地在prepareForSegue中做到这一点:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = sender.destination as? HasFoo {
vc.foo = "ho ho ho"
}
}

最新更新