gpt4 book ai didi

ios - 创建一个通用函数,该函数接受 View Controller 类型作为参数,并根据该类型返回自定义 View Controller

转载 作者:行者123 更新时间:2023-11-29 05:13:47 24 4
gpt4 key购买 nike

我正在尝试创建一个通用函数,它将 View Controller 类型作为参数并返回基于该类型的自定义 View Controller 。

func setUpInstance<T>(_ viewControllerType: T, toName: String?) -> T where T: UIViewController {

switch viewControllerType {

case is GetInstructionsModalViewController:
let getInstructionsVC = getViewController(GetInstructionsModalViewController.self, "Instructions", identifier: "GetInstructionsVC")
getInstructionsVC.delegate = self
getInstructionsVC.getDirectionsDelegate = self
getInstructionsVC.modalPresentationStyle = .overCurrentContext
moveButtonsAccordingToViewHeight(getInstructionsVC.height)

return getInstructionsVC as! T

case is TurnModalViewController:
let turnVC = getViewController(TurnModalViewController.self, "Turns", identifier: "TurnVC")
turnVC.modalPresentationStyle = .overCurrentContext
turnVC.delegate = self
turnVC.toName = toName
bottomContainer.isHidden = true
moveButtonsAccordingToViewHeight(turnVC.height)
return turnVC as! T

default:
return UIViewController.self as! T
}

}

当我尝试实例化自定义 View Controller 时:

let turnVC = setUpInstance(TurnModalViewController, toName: nil)

我收到错误:

Cannot convert value of type 'TurnByTurnModalViewController.Type' to expected argument type 'UIViewController'

知道如何让这个函数正常工作吗?

最佳答案

看起来您混淆了如何使用泛型。首先,您需要将函数的签名更改为

func setUpInstance<T>(_ viewControllerType: T.Type, toName: String?) -> T where T: UIViewController

因为您想检查输入类型并返回该类型的实例

然后使用正确的参数调用它

let turnVC = setUpInstance(TurnModalViewController.self, toName: nil)

关于ios - 创建一个通用函数,该函数接受 View Controller 类型作为参数,并根据该类型返回自定义 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59402120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com