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

后端 未结 4 1175
闹比i
闹比i 2021-01-23 08:58

So I\'m writing a lowpass accelerometer function to moderate the jitters of the accelerometer. I have a CGFloat array to represent the data and i want to damp it with this funct

4条回答
  •  一整个雨季
    2021-01-23 09:44

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

提交回复
热议问题