我想使用包含函数类型的元组数组.例如:
(Int,Bool,() -> () )
Run Code Online (Sandbox Code Playgroud)
然后我创建了数组:
var someList = [(Int,Bool,() -> () )]()
Run Code Online (Sandbox Code Playgroud)
但在编译时,此声明中有2个错误:
Expected ',' separatorExpected expression in list of expressions那么可以在元组上使用函数类型还是我会错过某些东西?
你可以这样做:
typealias TupleType = (Int, Bool, () -> Void)
var list = [TupleType]()
Run Code Online (Sandbox Code Playgroud)
不幸的是,尝试从阵列中访问元组中的项目会导致Playgrounds崩溃 - "与Playground服务的通信意外中断".在项目中尝试相同的操作会导致分段错误.如果您遇到同样的问题,我建议您改用结构:
struct MyStruct {
let num: Int
let bool: Bool
let closure: () -> Void
init(num: Int, bool: Bool, closure: () -> Void = {}) {
self.num = num
self.bool = bool
self.closure = closure
}
}
var list = [MyStruct]()
list.append(MyStruct(num: 1, bool: true, closure: { println("Hello") }))
list.append(MyStruct(num: 2, bool: false))
Run Code Online (Sandbox Code Playgroud)