[swift-users] inout params seem to have undefined behavior

David Sweeris davesweeris at mac.com
Sat Jun 11 13:57:00 CDT 2016


You can’t pass a `let` as an `inout` argument. I’d guess that’s what’s happening is the `arr[2]` part is creating a temporary var to which the `&` part then provides a reference. `b` is then dutifully modified in the function, but there’s no mechanism for copying it back into `arr` when `foo` returns, so the change isn’t reflected at the call site.

I *think* that the documentation you’re referring to in your last sentence is talking about when the value is updated at the call site. That is, `arr` itself isn’t updated until `foo` returns, but within `foo`, the argument `a` would have whatever value you assign it, whenever you assign it.

I think.

HTH (also, I hope I’m right… the only thing worse that no info is bad info)
- Dave Sweeris

> On Jun 11, 2016, at 12:29 PM, Karl Pickett via swift-users <swift-users at swift.org> wrote:
> 
> I don't believe the (spartan) docs address this case:
> 
> func foo(inout a: [Int], inout b: Int) {
>    let acopy = a
>    a = [4, 5, 6]
>    print(acopy)  // prints "[1, 2, 3]"
>    b = 99
>    print(a)   // prints "[4, 5, 6]"
>    print(acopy)  // prints "[1, 2, 99]" (e.g. a let variable changed!)
> }
> 
> var arr = [1,2,3]
> 
> foo(&arr, b: &arr[2])
> 
> print(arr)  // prints "[4, 5, 6]"
> 
> 
> Is this code "undefined", meaning the spec / doc doesn't specifically
> say what should be happening?  For instance, I can't believe a let
> variable gets changed.  The docs also say inout changes the original
> value when the function ends, not in the middle as is happening here.
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160611/7cac7cd6/attachment.html>


More information about the swift-users mailing list