簡體   English   中英

如何在 Swift 中定義使用 class 類型作為參數的 function?

[英]How to define function that uses class type as a parameter in Swift?

我只是嘗試執行以下操作:

func popTo(classType: AnyClass, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is classType }
    context?.popToViewController(controller, animated: true)
}

我需要像這樣使用它:

popTo(SettingsViewController.self, from: navigationController)

就編譯器而言, classType不是StringInt之類的類型。 它只是一個參數的名稱(它存儲一個類型)。 但是is運算符期望其 RHS 上有一個類型(可以在編譯時解析)。

我們需要一種在編譯時已知的類型。 我們可以用 generics 傳遞這樣一個類型參數:

func popTo<T>(classType: T.Type, from context: UINavigationController?) {
    if let controller = context?.viewControllers.first(where: { $0 is T }) {
        context?.popToViewController(controller, animated: true)
    }
}

您還可以添加約束T: AnyObject以更接近地反映原始代碼中的AnyClass (= AnyObject.Type ),但您不必特別這樣做。

func popTo<T: UIViewController>(classType: T.Type, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is T }
    context?.popToViewController(controller!, animated: true)
}

暫無
暫無

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

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