Swift Function That Takes in Array Giving Error: '@Lvalue $T24' Is Not Identical to 'Cgfloat'

Swift function that takes in array giving error: '@lvalue $T24' is not identical to 'CGFloat'

That code seems to compile if you pass the array with the inout modifier:

func lowPass(inout vector:[CGFloat]) -> [CGFloat] {
...
}

I'm not sure whether that's a bug or not. Instinctively, if I pass an array to a function I expect to be able to modify it. If I pass with the inout modifier, I'd expect to be able to make the original variable to point to a new array - similar to what the & modifier does in C and C++.

Maybe the reason behind is that in Swift there are mutable and immutable arrays (and dictionaries). Without the inout it's considered immutable, hence the reason why it cannot be modified.

Addendum 1 - It's not a bug

@newacct says that's the intended behavior. After some research I agree with him. But even if not a bug I originally considered it wrong (read up to the end for conclusions).

If I have a class like this:

class WithProp {
var x : Int = 1

func SetX(newVal : Int) {
self.x = newVal
}
}

I can pass an instance of that class to a function, and the function can modify its internal state

var a = WithProp()

func Do1(p : WithProp) {
p.x = 5 // This works
p.SetX(10) // This works too
}

without having to pass the instance as inout.
I can use inout instead to make the a variable to point to another instance:

func Do2(inout p : WithProp) {
p = WithProp()
}

Do2(&a)

With that code, from within Do2 I make the p parameter (i.e. the a variable) point to a newly created instance of WithProp.

The same cannot be done with an array (and I presume a dictionary as well). To change its internal state (modify, add or remove an element) the inout modifier must be used. That was counterintuitive.

But everything gets clarified after reading this excerpt from the swift book:

Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.

So when passed to a func, it's not the original array, but a copy of it - Hence any change made to it (even if possible) wouldn't be done on the original array.

So, in the end, my original answer above is correct and the experienced behavior is not a bug

Many thanks to @newacct :)

Bubble sorting an array in Swift, compiler error on swap

Function parameters are by default constant (as if declared with let).
If you want to modify the parameter inside your function, you have to declare it as a variable:

func sortCards(var cards: Array<Card>) -> Array<Card> { ...

Note that only the local parameter cards is modified, not the array passed as
an argument to the function (which seems to be your intention because the function
returns a new array).



Related Topics



Leave a reply



Submit