swift 如何在函数参数闭包中设置类?

qyzbxkaa  于 2023-02-07  发布在  Swift
关注(0)|答案(1)|浏览(96)

我想要达到的目标:

func test() {
  let myClass = MyClass().setup {
   $0.testClosure = {
     print("1 closure called")
   }

   $0.test2Closure = {
     print("2 closure called ")
   }
  }
}

这是我尝试,但我得到错误:* * 表达式的类型在没有更多上下文的情况下是模糊的**我只是想知道这样的事情是否可能?

class MyClass {
var testClosure: (() -> Void)
var test2Closure: (() -> Void)

func setup(_ setup: ((_ controller: MyClass) -> Void)) {
  setup(self)
}
rbpvctlc

rbpvctlc1#

这段代码看起来很复杂。为什么要有一个setup示例方法,它把类的另一个示例作为参数,然后用self调用它呢?这很令人困惑和奇怪。
这个更干净的设置怎么样?

class MyClass {
    typealias AClosure =  (() -> Void)
    var testClosure: AClosure?
    var test2Closure: AClosure?
    
    // Use this initializer if you want to assign the closures later
    init() {
    }
    
    // Use this intializer to provide the closures when you create an instance.
    init(testClosure: @escaping AClosure, test2Closure: @escaping AClosure) {
        self.testClosure = testClosure
        self.test2Closure = test2Closure
    }
}

func test() {
    let myClass = MyClass(
        testClosure: {
            print("1 closure called")
            
        },
        test2Closure: {
            print("2 closure called")
        }
    )
    myClass.testClosure?()
    myClass.test2Closure?()
}

test()

相关问题