拿这段代码:
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)
}
错误:
类型的价值&#39; T&#39;没有会员&some 39?someProperty&#39;
显然我知道它有,但我怎么写它(或测试它是否存在)?
答案 0 :(得分:1)
如果您知道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)
}