Swift 如果第一种类型失败,可选择向下转换到另一种类型

Swift 如果第一种类型失败,可选择向下转换到另一种类型,swift,optional,optional-chaining,Swift,Optional,Optional Chaining,我有一个类,其委托类型为UIViewController 此委托可以是UIViewController的2个子类之一。这两个子类都包含一个使用相同参数的同名方法 class TypeOne: UIViewController { method() { } } class TypeTwo: UIViewController { method() { } } 目前,我正在写这样的声明,当然它是有效的,但从枯燥的角度来看,它让我发疯 if let delegat

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

此委托可以是UIViewController的2个子类之一。这两个子类都包含一个使用相同参数的同名方法

class TypeOne: UIViewController {
    method() {

    }
}

class TypeTwo: UIViewController {
    method() {

    }
}
目前,我正在写这样的声明,当然它是有效的,但从枯燥的角度来看,它让我发疯

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

您正在描述一个协议:

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可以向编译器(以及您)保证此对象具有
方法
方法。因此,您可以调用该方法,而不必费心知道这是TypeOne还是TypeTwo。

您正在描述一个协议:

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可以向编译器(以及您)保证此对象具有
方法
方法。因此,您可以调用该方法,而不必费心知道这是TypeOne还是TypeTwo。

@matt谢谢,我试过了,但它的作用是相同的——将委托视为基础UIViewController@matt谢谢,我试过了,但它也一样-将代理视为基本UIViewControllert非常感谢。当然是最明显的,也可能是最干净的方法,非常感谢。绝对是最明显的,可能也是最干净的方法