在Swift中,可以通过以下几种方式将函数传递给另一个类:
class AnotherClass {
func performOperation(operation: () -> Void) {
// 执行传递进来的闭包
operation()
}
}
class MyClass {
func myFunction() {
let anotherClass = AnotherClass()
anotherClass.performOperation {
print("Hello, World!")
}
}
}
protocol MyDelegate {
func performOperation()
}
class AnotherClass {
var delegate: MyDelegate?
func performOperation() {
delegate?.performOperation()
}
}
class MyClass: MyDelegate {
func myFunction() {
let anotherClass = AnotherClass()
anotherClass.delegate = self
anotherClass.performOperation()
}
func performOperation() {
print("Hello, World!")
}
}
class AnotherClass {
func performOperation() {
NotificationCenter.default.post(name: NSNotification.Name("MyNotification"), object: nil)
}
}
class MyClass {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: NSNotification.Name("MyNotification"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func handleNotification() {
print("Hello, World!")
}
func myFunction() {
let anotherClass = AnotherClass()
anotherClass.performOperation()
}
}
以上是将函数传递给Swift中另一个类的几种常见方式。根据具体的场景和需求,选择合适的方式来实现函数的传递。
领取专属 10元无门槛券
手把手带您无忧上云