简体   繁体   English

将委托设置为类类型而不是Swift中的实例

[英]Set delegate to class type not to instance in Swift

In Objective-C it was possible to set a class as a delegate (not an instance of a class but a pure class). 在Objective-C中,可以将一个类设置为委托(不是类的实例,而是纯类)。 Is it possible in Swift? 在Swift中有可能吗?

Yes it is 是的

Declare a delegate variable to be a class type, not instance type. delegate变量声明为类类型,而不是实例类型。
I also make it optional, but we could also make it non-optional and pass it in the init method. 我也将其设置为可选,但是我们也可以将其设置为非可选,然后将其传递给init方法。

var delegate : Int.Type? 

Code Example 代码示例

class A {
  static func sayHello() {
    println("Hello")
  }
}

class B {
  var num = 10
  var delegate : A.Type?
  func hi() {
    delegate?.sayHello()
  }
}

var b = B()
b.delegate = A.self
b.hi()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM