簡體   English   中英

如何在Swift中檢查實例的類型?

[英]How can I check an instance's type in Swift?

我想使用展開搜索從當前UIViewController導航到第二個呈現UIViewController

let unwindDestinationViewController = self.presentingViewController!.presentingViewController!
                    switch unwindDestinationViewController{
                    case is UIViewControllerSubclass:
                        self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
                        break
                    default:
                        break
                    }

但是,這不起作用。 我還嘗試將case語句更改為UIViewControllerSubclass.Type但它給了我一個錯誤: cast from UIViewController to unrelated type UIViewControllerSubclass always fails.

如果有人能告訴我我做錯了,我將不勝感激。

您的代碼對於檢查類型是正確的:

case is UIViewControllerSubclass:

測試類的另一種方法:

case let vc as UIViewControllerSubclass:

如果您需要訪問特定於該類的方法或屬性,這將很有幫助。

如果您不需要使用vc ,請執行以下操作:

case _ as UIViewControllerSubclass:

您可以在此處使用if語句:

if unwindDestinationViewController is UIViewControllerSubclass {
    self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM