swift中的objc的"UIViewController< MyProtocol>"等效项是什么? [英] What is the equivalent of `UIViewController<MyProtocol>` of objc in swift?

查看:67
本文介绍了swift中的objc的"UIViewController< MyProtocol>"等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个函数,该函数接受采用特定协议的UIViewController.如何迅速声明呢?

I want to declare a function that accepts an UIViewController that adopts a particular protocol. How can I declare this in swift?

protocol MyProtocol {
    func subtitle() -> String
    func saveResults()
}

func setupViewController(controller: UIViewController<MyProtocol> ) { // ERROR here
    ...
}

我为什么要这样做:
因为我创建了一个容器视图控制器,该控制器具有多个不同类的子代.它们的共同点是MyProtocol,而偏离它们继承(直接或间接)UIViewController的事实.

Why I want to do this:
Because I have created a container view controller that has several children of different classes. What they have in common is MyProtocol and off-course the fact they inherit (directly or indirectly) UIViewController.

因此,我的方法之一将其中一个控制器作为参数.我想告诉编译器最可能的信息:该对象是UIViewController并符合MyProtocol.我该如何声明?

So one of my methods has one of this controllers as a parameter. I want to tell the compiler the most specific information possible: the object is an UIViewController and conforms to MyProtocol. How Can I declare this?

推荐答案

我不太了解Objective-C,但看起来甚至比您使用泛型来满足您的要求(肯定地说这是因为我不知道obj-​​c中的泛型语法.在快速使用泛型时,您的setupViewController函数应如下所示:

I don't understand objective-c well but it looks than even in it you use generics to achieve what you are asking for (cant say that for sure because I have no idea about generics syntax in obj-c). In swift using generics your setupViewController function should like this:

func setupController<T:UIViewController where T:MyProtocol>(controller : T){

}

并且在功能上完全等同于Objective-c的方法

and this in functionality terms is completely equivalent with method from objective-c

这篇关于swift中的objc的"UIViewController&lt; MyProtocol&gt;"等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆