ios - 将参数传递给实现协议(protocol)并快速扩展类的方法

标签 ios templates generics swift protocols

在 Objective-C 中,您可以通知编译器类型应该是特定类的后代,并且还符合协议(protocol)(例如“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”。我不能将泛型与“具体的”、未参数化的类一起使用吗?我仍在思考这部分语言,感谢您的帮助。

最佳答案

假设您希望 MyViewController 是实现 MyProtocolUIViewController 的任何子类 请注意,确实没有一种干净的方法来获取回到 UIViewController 方法,不添加任何与协议(protocol)相关的内容。

我想你要找的是:

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 在这种情况下实际上不需要参数。

关于ios - 将参数传递给实现协议(protocol)并快速扩展类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198473/

相关文章:

java - PECS 不适用于具有接口(interface)的返回类型

ios - 设备无法识别此主机。尝试使用 iOS 7.1 的 iphone 4 时

c++ - 模板非类型参数+左值/右值

templates - GoLang 在模板索引中挂起

c++ - 好友功能和模板

c# - C# 中的通用输入参数?

.net - LINQ : Generics with IQueryable

ios - 使用 Facebook IOS SDK 共享到提要时更改 defaultAudience

ios - NSURLSession/NSURLConnection HTTP 加载在 Swift 4 上失败

ios - 在原生 iOS7 应用程序中使用 fontello 字体