如何使用参数作为参数传递闭包并执行它?

Man*_*uel 6 closures function swift

类的初始化器A采用可选的闭包作为参数:

class A {
   var closure: ()?

   init(closure: closure()?) {
      self.closure = closure
      self.closure()
   }
}
Run Code Online (Sandbox Code Playgroud)

我想传递一个带有参数的函数作为闭包:

class B {
    let a = A(closure: action(1)) // This throws the error: Cannot convert value of type '()' to expected argument type '(() -> Void)?'

    func action(_ i: Int) {
       //...
    }
}
Run Code Online (Sandbox Code Playgroud)

A应该action使用参数执行闭包i.

我不确定如何正确编写,请参阅上面的代码注释中的错误.有什么需要改变?

OOP*_*Per 7

请使您的“现在拥有”代码没有错误。

假设您的班级A是这样的:

class A {
    typealias ClosureType = ()->Void

    var closure: ClosureType?

    init(closure: ClosureType?) {
        self.closure = closure
        //`closure` would be used later.
    }

    //To use the closure in class A
    func someMethod() {
        //call the closure
        self.closure?()
    }
}
Run Code Online (Sandbox Code Playgroud)

有了A上面的给定,您需要将您的类重写B为:

class B {
    private(set) var a: A!
    init() {
        //initialize all instance properties till here
        a = A(closure: {[weak self] in self?.action(1)})
    }

    func action(i: Int) {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)


mat*_*att 6

问题是这closure()?不是一种类型.并且()?是一种类型,但它可能不是您想要的类型.

如果您希望var closure将某个函数作为其值,则需要在声明中使用该函数的类型,例如

var closure: (Int) -> Void
Run Code Online (Sandbox Code Playgroud)

类似地,如果您想init(closure:)将某个函数作为其参数,则需要在声明中使用该函数的类型,例如

init(closure: (Int) -> Void) {
Run Code Online (Sandbox Code Playgroud)

  • matt:我很高兴你在这里(非主题),但我很沮丧:如果你有时间,你对我对[这个问题]的评论有任何评论/解释(http:// stackoverflow. com/questions/38336982/is-a-a-a-way-to-test-if-you-match-a-set-of-enumements#comment64091487_38336982),关于我认为是等价的case ...``switch`语句中的模式匹配与模式匹配使用`if case ...`(我可以发布一个单独的问题,但它会非常接近于我评论过的问题). (2认同)