如果第一个失败,则可选向下转换为另一种类型

问题描述 投票:0回答:1

我有一个类,其委托类型为UIViewController

此委托可以是UIViewController的2个子类之一。这两个子类都包含一个具有相同名称且带有相同参数的方法。

class TypeOne: UIViewController {
    method() {

    }
}

class TypeTwo: UIViewController {
    method() {

    }
}

当前,我正在编写这样的语句,虽然它确实有效,但是从DRY的角度来看,这使我不寒而栗。

if let delegate = delegate as? TypeOne {
    delegate.method()
} else if let delegate = delegate as? TypeTwo {
    delegate.method()
}

我想做类似的事情

if let delegate = delegate as? TypeOne ?? delegate as TypeTwo {
    delegate.method()
}

但是上面的内容实际上并没有降低委托,因为我收到一个错误,指出类型UIViewController不包含'method'

还有其他方法,如果第一个失败失败,请尝试第二个失败,并且将委托视为任一类型,而不是基数UIViewController,则我将如何进行链接?

swift optional optional-chaining
1个回答
0
投票

您正在描述协议:

protocol MethodHolder {
    func method()
}
class TypeOne: UIViewController, MethodHolder {
    func method() {
    }
}
class TypeTwo: UIViewController, MethodHolder {
    func method() {
    }
}
class ActualViewController : UIViewController {
    var delegate : MethodHolder?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate?.method() // no need to cast anything!
    }
}

不需要进行任何转换,因为将委托作为MethodHolder输入可以向编译器(和您)保证该对象具有method方法。因此,您可以调用该方法而不必费心知道这是TypeOne还是TypeTwo。

© www.soinside.com 2019 - 2024. All rights reserved.