modify an array within a function does not work

前端 未结 4 844
情深已故
情深已故 2021-01-27 12:00

I call a function to process and modify an array. But the array does not change at all. Looks like a Swift major bug ???

var Draw_S = [String]();
var Draw_E =          


        
相关标签:
4条回答
  • 2021-01-27 12:06

    The arrays inside alter_them are a copy of the originals.

    Use inout to modify the original arrays:

    func alter_them(inout data: [String], inout data2: [String]){
        for (i, _) in data.enumerate(){
            data[i] = "1"
        }
        for (i, _) in data2.enumerate(){
            data2[i] = "2"
        }
    }
    
    alter_them(&Draw_S, data2: &Draw_E)
    
    0 讨论(0)
  • 2021-01-27 12:06

    You have misunderstood how arrays work in Swift. They are value types, which is unlike Objective-C where they are reference types.

    What this means is that the function alter_them gets a copy of the arrays and you are actually modifying the copy.

    You will need to return the modified versions from the alter_them function and re-assign Draw_S and Draw_E.

    FWIW instance variables usually start with a lowercase character i.e. draw_S

    0 讨论(0)
  • 2021-01-27 12:14

    This is not a bug. This is because arrays of strings in Swift are defined as structs and are therefore value types.

    The function is modifying the array that is passed in as a parameter but that is a copy of the array Draw_S and so on.

    You need to define them as inout parameters if you want the function to modify the existing array but that breaks the way Swift works. You'd be better passing a result array out and storing that instead.

    0 讨论(0)
  • 2021-01-27 12:26

    Both String and Array are value types in Swift. That is the reason why it is not modified inside a method. You would need to return the modified array back from the method.

    0 讨论(0)
提交回复
热议问题