是否有可能创造称取&QUOT函数数组,INOUT"在斯威夫特的参数? [英] Is it possible to create an array of functions that take "inout" parameters in Swift?

查看:150
本文介绍了是否有可能创造称取&QUOT函数数组,INOUT"在斯威夫特的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了,我觉得可能是一个错误的东西。斯威夫特可以让你创建一个函数数组,像这样:

I am running into something that I think might be a bug. Swift lets you create an array of functions, like this:

func example1(a: Int) {
    println(a)
}

let functionArray1 = [example1]

println(functionArray1[0](3))      // This prints "3"

但是,如果我尝试创建的是采取 INOUT 参数功能一个数组,我得到了可怕的分段故障11

But if I try to create an array of functions that take an inout parameter, I get the dreaded segmentation fault 11:

func example2(inout a: Int) {
    println(a)
}

let functionArray2 = [example2]  // This produces the seg fault

这没有什么区别,如果我确实操纵 A 在函数内部或没有。

有谁知道是怎么回事呢?有没有办法通过使用合适的类型标注,或其他一些窍门来创建功能与 INOUT 参数数组?

Does anyone know what is going on here? Is there a way to create an array of functions with an inout parameter by using an appropriate type annotation, or some other trick?

编辑:我曾尝试为阵列提供了一个类型注释 - 不解决问题:

I have tried providing a type annotation for the array - that does not solve the problem:

let functionArray2: [(inout Int) -> ()] = [example2]   // Same error...

我也试着写的函数作为闭包(用显式类型的注释),然后加入封到一个数组,也没有成功。

I have also tried writing the function as a closure (with an explicit type annotation) and then adding the closure to an array, also with no success.

推荐答案

关于这一问题的评论所指出的那样,这确实出现了与雨燕的操控的INOUT 类型签名某些情况下。

As the comments on the question have pointed out, this does appear to be a bug relating to Swift's handling of inout in type signatures for some cases.

直到错误得到解决,你可以解决它通过使用 UnsafeMutablePointer

Until the bug is addressed, you can work around it by using an UnsafeMutablePointer.

func increment(a: UnsafeMutablePointer<Int>) {
    a.memory += 1
}
let functionArray = [increment]

var thing = 2
functionArray2[0](&thing)
println(thing) // 3

这篇关于是否有可能创造称取&QUOT函数数组,INOUT&QUOT;在斯威夫特的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆