取此代码:
func openStoryboardWithName<T: UIViewController>(name: String, asType type: T.Type) {
let storyboard = UIStoryboard(name: name, bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! T
controller.title = "test"
controller.someProperty = "some value"
presentViewController(controller, animated: true, completion: nil)
}
错误:
"T"类型的值没有成员"someProperty"
很明显,我知道它有,但我该如何向它写信(或者测试它是否存在)?
如果您知道T
有someProperty
,那么您需要以某种方式告诉编译器这一点。其中一种方法是使用这样的约束:
protocol HasSomeProperty: class {
var someProperty: String { get set }
}
func openStoryboardWithName<T: UIViewController where T: HasSomeProperty >(name: String, asType type: T.Type) {
let storyboard = UIStoryboard(name: name, bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! T
controller.title = "test"
controller.someProperty = "some value"
presentViewController(controller, animated: true, completion: nil)
}
另一种方法是子类UIViewController
,并在方法中使用该子类:
class UIViewControllerThatHasSomeProperty: UIViewController {
var someProperty = ""
}
func openStoryboardWithName<T: UIViewControllerThatHasSomeProperty>(name: String, asType type: T.Type) {
let storyboard = UIStoryboard(name: name, bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! T
controller.title = "test"
controller.someProperty = "some value"
presentViewController(controller, animated: true, completion: nil)
}