Swift - 具有类型和协议的属性 [英] Swift - Property with type and protocol

查看:32
本文介绍了Swift - 具有类型和协议的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个 Objective-C 类中,我有一个 UIViewController 类型的属性,我将如何在 Swift 中表示它?我需要从 UIViewControllerUIProfileListHeaderDelegate 访问属性和方法.

In one of my Objective-C clases, I have a property of type UIViewController<UIProfileListHeaderDelegate>, how would I represent this in Swift? I need to access properties and methods from both UIViewController and UIProfileListHeaderDelegate.

谢谢!

推荐答案

处理这个问题的快速方法是定义一个协议,其中包含来自 UIViewController 的相关方法,并让您的 UIProfileListHeaderDelegate 继承自那个.

The swift way to handle this is to define a protocol that includes the relevant methods from UIViewController and have your UIProfileListHeaderDelegate inherit from that.

用你关心的方法定义一个协议:

Define a protocol with the methods you care about:

protocol ViewControllerSubset {
    var view:UIView!
}

声明 UIViewController 实现了协议,不需要实际实现任何东西,因为它已经存在了

Declare that UIViewController implements the protocol, don't need to actually implement anything because it's already there

extension UIViewController : ViewControllerSubset {}

继承你的协议

protocol UIProfileListHeaderDelegate : ViewControllerSubset

你走吧.

如果你不想改变你的协议的层次结构(或者不能因为它是一个系统协议)你可以定义一个包含两个协议的协议)

If you don't want to change the hierarchy of your protocol (or can't because it's a system protocol) you can define a protocol that contains both protocols)

protocol EquatableAndComparable : Equatable, Comparable { }

这篇关于Swift - 具有类型和协议的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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