Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning function to a variable in swift strange behavior

I have the following simple segment of code:

func swapper(var arr: [Int]) {
    let first: Int = arr[0]
    let last: Int  = arr[arr.count - 1]
    arr[0] = last
    arr[arr.count - 1] = first
    arr
}
var myFunctionPointer : ([Int]) -> () = swapper

It is working well but when i try to add inout to the signature of the method's argument I was unable to assign it to variable outside like following.

func swapper(inout  arr: [Int]){
    let first: Int = arr[0]
    let last: Int  = arr[arr.count - 1]
    arr[0] = last
    arr[arr.count - 1] = first
    arr
}
var myFunctionPointer: ([Int]) -> () = swapper // This failed [int] is not subtype of inout [Int]
var myFunctionPointer: (inout[Int]) -> () = swapper // I am not getting a compilation error, but the playground keeps showing an error message and everything stopped working 

I am using Xcode 6.1 Playground.

Is the second way the right way but Xcode has a bug? any thoughts?

like image 798
A.Alqadomi Avatar asked Feb 12 '23 16:02

A.Alqadomi


2 Answers

This appears to be a bug in the playground. It works in a project without trouble.

It can be simplified, though (I realize this probably isn't your real code, but it offers a good example of better approaches):

func swapper(inout arr: [Int]){
  (arr[0], arr[arr.count - 1]) = (arr[arr.count - 1], arr[0])
}

//let myFunctionPointer : (inout [Int])->Void = swapper
let myFunctionPointer = swapper // There's no real reason for a type here

var x = [1,2,3]
myFunctionPointer(&x)
println(x)

Note that putting arr at the end of your function is not a good practice. Swift does not return the last value computed, so this line does nothing at all (but create some confusion).


EDIT: Actually, it can be even a little simpler than that (I didn't realize this would work until I tried it):

func swapper(inout arr: [Int]){
  swap(&arr[0], &arr[arr.count-1])
}
like image 122
Rob Napier Avatar answered Mar 08 '23 14:03

Rob Napier


The second version is using the correct syntax.

That's an Xcode bug/problem - I have repeated Error running playground and Communication with the playground service was interrupted unexpectedly notifications every time I save in a playground.

It looks like the playground has problems when using inout - I don't know if that's a recurring problem, but if you replace inout with var in the function declaration and remove inout from the closure declaration, it works. Disclaimer: this is just a playground verification test, not a solution

like image 27
Antonio Avatar answered Mar 08 '23 14:03

Antonio