Swift:if let 语句中的条件类型转换(as?,as!)

xoo*_*ler 3 swift

如果基类有多种可能性,建议将“as”与“if”结合使用的方法是什么,例如

var delegate:AnyObject?

func myFunction(){

if let delegate = self.delegate as? A1ViewController {
  delegate.callFunction()
}

if let delegate = self.delegate as? A2ViewController{
   delegate.callFunction()
}
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将上面的两个 if 语句结合起来?

例如

if let delegate = self.delegate as? A1ViewController || let delegate = self.delegate = self.delegate as? A2ViewController {
   delegate.callFunction()
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*rrù 5

无论您想要实现什么目的(在我看来,如果您需要,您的代码设计中存在一些问题),这是我为此类检查编写最干净代码的 2 美分。

您当前不能 OR 两个let ... = ...语句。无论如何,您都可以解决创建一个包含公共调用的公共协议、扩展类并使用单个代码路径的问题。

protocol CommonDelegateProtocol { 
    func callFunction()
}

extension A1ViewController : CommonDelegateProtocol {}
extension A2ViewController : CommonDelegateProtocol {}

// then...

if let delegate = self.delegate as? CommonDelegateProtocol {
   delegate.callFunction()
}
Run Code Online (Sandbox Code Playgroud)

在不同代码路径的情况下带有开关的版本。

如果您需要不同的代码路径,这是我最好的选择。通过这种方式,您还可以强制您的代码评估所有可能的情况。

switch self.delegate {
case let d as A1ViewController:
    // "d" is of type A1ViewController
    d.callA1Function()
case let d as A2ViewController:
    // "d" is of type A2ViewController
    d.callA2Function()
default:
    print("Uncovered case")
}
Run Code Online (Sandbox Code Playgroud)