我已经制定了下面的函数,以便我可以在我的ios应用程序中重复使用它。 但是,我无法构建我的应用程序,因为我下面的函数向我指示了错误,但我看不出它有什么问题。 该函数旨在将用户移动到 ios 应用程序中的新页面。 请问有人可以建议吗?
func goToPage(goto storyBoardId: String, ofType typeUIViewController: UIViewController.Type) -> UIViewController {
let storyBoard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let newPage = storyBoard.instantiateViewController(withIdentifier: storyBoardId) as! typeUIViewController // Error: use of undeclared type 'typeUIViewController'
self.present(newPage, animated: true, completion: nil)
return newPage
}
您的函数需要 UIViewController
类型的返回值,而您不返回任何内容。因此,请返回您创建的实例(如果需要)。或者删除返回值。
使用泛型对函数进行了略微修改的变体,它正好可以满足您的需求。函数前面的@discardableResult
字告诉编译器可以省略结果。
@discardableResult
func goToPage<T>(goto storyBoardId: String,
ofType typeUIViewController: T.Type) -> T
where T: UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newPage = storyboard.instantiateViewController(withIdentifier: storyBoardId) as! T
self.present(newPage, animated: true, completion: nil)
return newPage
}
用法
// Ignore return value
goToPage(goto: "Page", ofType: ViewController.self)
// Preserve return value:
// Thanks to generics, page and page2 types are inferred by the compiler
// page is CustomController and page2 is LoginController
// and you can access corresponding interface:
var page = goToPage(goto: "Page", ofType: CustomController.self)
var page2 = goToPage(goto: "Page", ofType: LoginController.self)
更新
我看到 Honey 提出了正确的想法,但类型转换的问题仍然存在。原因是编译器不知道typeUIViewController
是哪种类型。事实上,它实际上甚至不是一个类型,它只是变量的内部名称。而且编译器无法推断出它的类型(与运算符一起使用as
)。因此,实现您正在尝试的正确方法之一是使用泛型。将通用T
视为满足特定条件的模式。
您需要将UIViewController
更改为UIViewController.Type
。欲了解更多信息,请看这里
因为参数 UIViewController
可以接受UIViewController
实例,例如 UIViewController()
.但是,您需要获取其类型信息(您不需要实例),因此它必须是类型 UIViewController.Type
的参数,因此您传递的值可以是类似于 SomeUIViewControllerSubclass.self
它不是实例......
所以你必须这样做:
func goToPage(goto storyBoardId: String, ofType typeUIViewController: UIViewController.Type) -> UIViewController {
let storyBoard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
let newPage = storyBoard.instantiateViewController(withIdentifier: storyBoardId) as! typeUIViewController
self.present(newPage, animated: true, completion: nil)
}