【问题标题】:Delegate Declaration Swift代表声明 Swift
【发布时间】:2016-09-15 14:40:15
【问题描述】:
在 Objective C 中我们可以这样声明一个委托
@property (nonatomic, weak) id<SomeProtocol> delegate
很快
weak var delegate : SomeProtocol?
但在 Objective C 中,我们可以强制委托属于某个类:
@property (nonatomic, weak) UIViewController<SomeProtocol> delegate
我如何快速做到这一点?
【问题讨论】:
标签:
objective-c
swift
delegates
【解决方案1】:
Swift 要求您在编译时知道类型的大小,因此您需要使您的类对您的委托类型具有通用性:
protocol SomeProtocol: class {}
class SomeClass<T: UIViewController> where T: SomeProtocol {
weak var delegate : T?
}
还有另一种选择,如果你真的不关心它被限制到某个类型,而是某个接口,你可以通过另一个协议来描述 UIViewController,它会公开你需要的方法。
protocol UIViewControllerProtocol: class,
NSObjectProtocol,
UIResponderStandardEditActions,
NSCoding,
UIAppearanceContainer,
UITraitEnvironment,
UIContentContainer,
UIFocusEnvironment {
var view: UIView! { get set }
func loadView()
func loadViewIfNeeded()
var viewIfLoaded: UIView? { get }
}
extension UIViewController: UIViewControllerProtocol {}
protocol SomeProtocol: class {}
class SomeClass {
weak var delegate : SomeProtocol & UIViewControllerProtocol?
}
这将允许您使用 UIViewController 中的许多方法和属性,但它并不会真正将您的委托限制为 UIViewController,因为任何其他对象都可以实现此协议并被使用。
PS:这是 Swift 3.0