[英]Is it possible to create an array of functions that take “inout” parameters in Swift?
我遇到了我認為可能是錯誤的問題。 Swift可讓您創建函數數組,如下所示:
func example1(a: Int) {
println(a)
}
let functionArray1 = [example1]
println(functionArray1[0](3)) // This prints "3"
但是,如果我嘗試創建帶有inout
參數的函數數組,則會出現可怕的segmentation fault 11
:
func example2(inout a: Int) {
println(a)
}
let functionArray2 = [example2] // This produces the seg fault
這沒有什么區別,如果我確實操縱a
函數內部與否。
有人知道這是怎么回事嗎? 有沒有一種方法可以通過使用適當的類型注釋或其他技巧來創建帶有inout
參數的函數數組?
編輯:我試圖為數組提供類型注釋-無法解決問題:
let functionArray2: [(inout Int) -> ()] = [example2] // Same error...
我還嘗試過將函數編寫為閉包(帶有顯式類型注釋),然后將閉包添加到數組中,但也沒有成功。
正如對該問題的評論所指出的那樣,在某些情況下,這確實是與Swift處理類型簽名中的inout
有關的錯誤。
在解決該錯誤之前,您可以使用UnsafeMutablePointer
來解決它。
func increment(a: UnsafeMutablePointer<Int>) {
a.memory += 1
}
let functionArray = [increment]
var thing = 2
functionArray2[0](&thing)
println(thing) // 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.