如何在线声明委托?
How to declare a delegate in-line?
在 Java 中有一个模式,可以在其中声明一个委托,而不是让父 class 符合接口:
例如:
public class MyClass {
interface Delegate {
void completion(Boolean succeeded);
}
void doSomething(Delegate delegate) {
delegate.completion(true);
}
void myMethod() {
doSomething(new Delegate() { // <-- declared in-line
@Override
public void completion(Boolean succeeded) {
// ...
}
});
}
}
在 Swift 中,我可以使 MyClass
符合 Delegate
协议并覆盖 class 级别的委托方法。我怎样才能像 Java 模式那样在线执行此操作?
在 Swift 中,您不能定义内联协议(在另一个类型中,例如 Class
、Struct
或 Enum
)。
然而,有一个更现代的解决方案应该非常接近您正在寻找的解决方案:Closures。
闭包
class MyClass {
// define your closure, make it as complex as you want
typealias CompletionType = (Bool) -> ()
// this method accepts a closure as parameter and will call it
func doSomething(completion: @escaping CompletionType) {
completion(true)
}
}
测试
let myClass = MyClass()
myClass.doSomething { result in
print(result)
}
输出
true
Swift 没有匿名 classes 的概念。但是它有嵌套 classes 的概念。你可以这样写:
func myMethod() {
class DelegateImpl: Delegate { ... }
doSomething(DelegateImpl())
}
但是请注意,委托通常被声明为 weak
,这意味着新分配的实例将立即被释放。这与 class 的声明方式无关(即嵌套而不是内联),而是与 Swift(又名 ARC)的内存管理规则有关。
但是,正如其他人指出的那样,闭包可能更适合这种功能。
在 Java 中有一个模式,可以在其中声明一个委托,而不是让父 class 符合接口:
例如:
public class MyClass {
interface Delegate {
void completion(Boolean succeeded);
}
void doSomething(Delegate delegate) {
delegate.completion(true);
}
void myMethod() {
doSomething(new Delegate() { // <-- declared in-line
@Override
public void completion(Boolean succeeded) {
// ...
}
});
}
}
在 Swift 中,我可以使 MyClass
符合 Delegate
协议并覆盖 class 级别的委托方法。我怎样才能像 Java 模式那样在线执行此操作?
在 Swift 中,您不能定义内联协议(在另一个类型中,例如 Class
、Struct
或 Enum
)。
然而,有一个更现代的解决方案应该非常接近您正在寻找的解决方案:Closures。
闭包
class MyClass {
// define your closure, make it as complex as you want
typealias CompletionType = (Bool) -> ()
// this method accepts a closure as parameter and will call it
func doSomething(completion: @escaping CompletionType) {
completion(true)
}
}
测试
let myClass = MyClass()
myClass.doSomething { result in
print(result)
}
输出
true
Swift 没有匿名 classes 的概念。但是它有嵌套 classes 的概念。你可以这样写:
func myMethod() {
class DelegateImpl: Delegate { ... }
doSomething(DelegateImpl())
}
但是请注意,委托通常被声明为 weak
,这意味着新分配的实例将立即被释放。这与 class 的声明方式无关(即嵌套而不是内联),而是与 Swift(又名 ARC)的内存管理规则有关。
但是,正如其他人指出的那样,闭包可能更适合这种功能。