在 Swift 中,我可以在元组中使用函数类型吗?

In Swift, can I use function type in tuple?

我想使用包含函数类型的元组数组。例如:

(Int,Bool,() -> () )

然后我创建数组:

var someList = [(Int,Bool,() -> () )]()

但是在编译时这条语句有 2 个错误:

所以可以在元组上使用 函数类型 还是我错过了什么?

你可以这样做:

typealias TupleType = (Int, Bool, () -> Void)
var list = [TupleType]()

不幸的是,试图从数组中访问元组中的项目 结果导致 Playgrounds 崩溃 - 'Communication with the Playground service was unexpectedly interupted'。在项目中尝试相同的事情会导致分段错误。如果您遇到同样的问题,我建议您改用结构:

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))

我认为这里有两个问题:1) 要求在元组声明中对函数类型使用 typealias,2) 元组中存储的取消引用函数的编译器错误。

1。添加功能

编译器不喜欢在元组声明中查找函数签名。这对我来说感觉像是一个错误,但我对 Swift 规范的了解还不足以确定。

typealias VoidToVoid = () -> ()

var c = [Int, Bool, VoidToVoid]()  // works
var d = [Int, Bool, () -> ()]()    // syntax error

2。尝试取消引用该函数时,编译器会出现段错误。

func performSideEffects() {
    println("Howdy")
}

c.append(1, true, performSideEffects)  // works
c.count  // works
c[0].2   // blows up. Although possible completions with correct type shows up

0  swift                    0x00000001020272b8 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x0000000102027794 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff8131ff1a _sigtramp + 26
3  libsystem_platform.dylib 0x00007fff5e2f0550 _sigtramp + 3707569744
4  swift                    0x00000001019ea39d swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 9901
5  swift                    0x0000000101954f4f swift::irgen::IRGenModule::emitGlobalTopLevel() + 159
6  swift                    0x00000001019d4c59 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 2121
7  swift                    0x00000001019d5693 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
8  swift                    0x0000000101911087 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 6647
9  swift                    0x000000010190f4e6 main + 1814
10 libdyld.dylib            0x00007fff829f15c9 start + 1
11 libdyld.dylib            0x000000000000003b start + 2103503475