代表声明斯威夫特

时间:2016-09-15 14:40:16

标签: objective-c swift delegates

在Objective C中,我们可以用这种方式声明委托

@property (nonatomic, weak) id<SomeProtocol> delegate

并在swift中

weak var delegate : SomeProtocol?

但是在Objective C中我们可以强制委托成为某个类:

@property (nonatomic, weak) UIViewController<SomeProtocol> delegate

我如何在swift中做到这一点?

1 个答案:

答案 0 :(得分:0)

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

相关问题