我试图创建一个自定义Action对象数组,每个对象都有一个可以在以后调用的闭包。我在这做错了什么?我该怎么办关闭?
let actionOne = Action(title: "1", image: "blue") {
println("1 blue")
}
let actionTwo = Action(title: "2", image: "yellow") {
println("2 yellow")
}
var actions: Array<Action> = [actionOne, actionTwo]
// how to run the closure from actionOne?
actionOne.closure() // compile error: invalid use of '()' to call a value of a non-function type '()?'
-----
class Action {
var title: String?
var image: String?
var closure: ()?
init(title: String, image: String, closure: () -> ()) {
self.title = title
self.image = image
self.closure = closure()
}
}
答案 0 :(得分:2)
class Action {
let title: String
let image: String
let closure: () -> ()
init(title: String, image: String, closure: () -> ()) {
self.title = title
self.image = image
self.closure = closure
}
}
let actionOne = Action(title: "1", image: "blue") {
println("1 blue")
}
let actionTwo = Action(title: "2", image: "yellow") {
println("2 yellow")
}
var actions: Array<Action> = [actionOne, actionTwo]
actionOne.closure()