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.
我不确定如何正确编写,请参阅上面的代码注释中的错误.有什么需要改变?
请使您的“现在拥有”代码没有错误。
假设您的班级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)
问题是这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)