类A
的初始化器以可选闭包作为参数:
class A {
var closure: ()?
init(closure: closure()?) {
self.closure = closure
self.closure()
}
}
我想传递一个带有参数的函数作为闭包:
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) {
//...
}
}
类A
应该使用参数i
执行闭包action
。
我不知道如何正确地写这个,见上面代码注释中的错误。有什么需要改变的?
发布于 2016-07-12 21:35:36
请使您的“什么-你有-现在”代码错误。
假设您的类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?()
}
}
在上面给出了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) {
//...
}
}
发布于 2016-07-12 21:24:19
类型作为参数
在Swift中,每个对象都有一个类型。例如,Int
、String
等可能是您非常熟悉的所有类型。
因此,当您声明一个函数时,应该指定任何参数的显式类型(有时是协议)。
func swallowInt(number: Int) {}
复合类型
Swift也有一个复合类型的概念。这方面的一个例子是元组。元组只是其他类型的集合。
let httpStatusCode: (Int, String) = (404, "Not Found")
函数可以很容易地将元组作为其参数:
func swallowStatusCode(statusCode: (Int, String)) {}
另一种复合类型是函数类型。函数类型由参数元组和返回类型组成。因此,上面的swallowInt
函数将具有以下函数类型:(Int) -> Void
。类似地,接受Int
和String
并返回Bool
的函数将具有以下类型:(Int, String) -> Bool
。
函数类型作为参数
因此,我们可以使用这些概念重写函数A:
class A {
var closure: (() -> Void)?
init(closure: (() -> Void)?) {
self.closure = closure
self.closure()
}
}
然后,传递一个论点就是:
func foo(closure: (Int) -> Void) {
// Execute the closure
closure(1)
}
发布于 2016-07-12 21:20:44
我认为您正在尝试的一种方法是使用以下代码:
class ViewController: UIViewController {
override func viewDidLoad() {
let _ = A.init(){Void in self.action(2)}
}
func action(i: Int) {
print(i)
}
}
class A: NSObject {
var closure : ()?
init(closure: (()->Void)? = nil) {
// Notice how this is executed before the closure
print("1")
// Make sure closure isn't nil
self.closure = closure?()
}
}
https://stackoverflow.com/questions/38338765
复制相似问题