【问题标题】:Passing parameter to method which implements protocol and extends a class in swift将参数传递给实现协议并快速扩展类的方法
【发布时间】:2015-01-28 17:22:04
【问题描述】:

在 Objective-C 中,您可以通知编译器类型应该是特定类的后代,并且还符合协议(例如“UIViewController *foo = nil”)。

我正在尝试用 Swift 做类似的事情,看起来这需要使用泛型。这是我期望的工作:

import UIKit

protocol MyProtocol {
    var foo: String {get set}
}

class MyViewController: UIViewController, MyProtocol {
    var foo: String = ""
}

func doAThing<T: UIViewController where T: MyProtocol>(vc: T) -> T? {
    var myViewController: T? = nil

    myViewController = MyViewController(nibName: nil, bundle: nil)

    return myViewController
}

我得到的错误是:“MyViewController”不能转换为“T”。我不能将泛型与“具体”、未参数化的类一起使用吗?我仍在研究这部分语言,感谢您的帮助。

【问题讨论】:

  • MyView的声明是什么?
  • 我编辑了我的帖子,它应该是 MyViewController。

标签: ios templates generics swift protocols


【解决方案1】:

假设您希望MyViewController 是实现MyProtocolUIViewController 的任何子类请注意,除了添加与协议相关的任何内容之外,实际上没有一种干净的方法可以返回UIViewController 方法。

我认为您正在寻找的是:

protocol MyProtocol {
    var foo: String {get set}
}

class MyViewController: UIViewController, MyProtocol {
    var foo: String = ""
}

class MyOtherViewController : UIViewController, MyProtocol {
    var foo = "My other view controller"
}

func doAThing<T: UIViewController where T: MyProtocol>() -> T? {
    return T(nibName: nil, bundle: nil)
}

let myViewController : MyViewController? = doAThing()
let myOtherViewController : MyOtherViewController? = doAThing()

let myProtocol : MyProtocol? = myViewController

由于允许 swift 函数覆盖仅根据返回类型而不同,并且类型推断能够在它们之间进行选择,doAThing 在这种情况下实际上不需要参数。

【讨论】:

  • 谢谢,这回答了我上面的具体问题 :) 我还想做的事情是根据一组规则选择和设置一个特定的视图控制器。我可能会发布一个后续问题...
  • 如果后续是“如何声明对实现 MyProtocol 的 UIViewController 子类的引用,以便我可以使用 viewController.view?”答案几乎是“你不能”此时的最佳实践似乎是将有趣的 UIViewController 方法添加到 MyProtocol。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多