swift泛型:如何将数据传递给目标实例变量

时间:2015-12-08 17:57:58

标签: swift generics

拿这段代码:

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;

显然我知道它有,但我怎么写它(或测试它是否存在)?

1 个答案:

答案 0 :(得分:1)

如果您知道TsomeProperty,那么您需要以某种方式告诉编译器。其中一种方法是使用这样的约束:

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)
}