Swift 方法链接,如何重用 类 和方法?

Swift method chaining, how to reuse classes and methods?

考虑以下示例

class ClassA {
    
    func createAnInstanceOfAnotherClass() -> AnotherClass {

        return AnotherClass()
    }
    
    func callMeA() {
        
    }
}

class ClassB {
    func createAnInstanceOfAnotherClass() -> AnotherClass {

        return AnotherClass()
    }
    
    func callMeB() {
        
    }
}

class AnotherClass {
    func doSomethingAndReturn() {
        return
    }
}

class MethodChain {
    func methodChainTest() {
        ClassA()
            .createAnInstanceOfAnotherClass()
            .doSomethingAndReturn() //return to ClassA
            .callMeA() // call classA callMe
        
        ClassB()
            .createAnInstanceOfAnotherClass()
            .doSomethingAndReturn() // return to ClassB
            .callMeB() // call ClassB callMe
    }
}

class AnotherClass 是否可以 return 创建它的 class 的实例? 在此示例中,我想在与 ClassA 和 ClassB 进行方法链接时使用 class 方法 doSomethingAndReturn,然后使用 ClassA 或 ClassB

中的方法连接方法链

您可以使 AnotherClass 具有类型参数 Creator 的泛型,它存储其创建者的类型。

class ClassA {
    
    func createAnInstanceOfAnotherClass() -> AnotherClass<ClassA> {

        return AnotherClass(creator: self)
    }
    
    func callMeA() {
        
    }
}

class ClassB {
    func createAnInstanceOfAnotherClass() -> AnotherClass<ClassB> {

        return AnotherClass(creator: self)
    }
    
    func callMeB() {
        
    }
}

class AnotherClass<Creator: AnyObject> {
    // weak to avoid retain cycles!
    private weak var creator: Creator?
    
    init(creator: Creator) {
        self.creator = creator
    }
    
    func doSomethingAndReturn() -> Creator {
        // assuming you always do method chaining, 
        // and not do something weird with the intermediate results,
        // this should be safe to unwrap forcefully
        creator!
    }
}