Swift pass struct by reference?

后端 未结 2 924
有刺的猬
有刺的猬 2020-12-31 01:15

I\'ve looked to similar questions but I haven\'t seen an answer that I am satisfied with.

Is it possible or advisable to pass structs by reference? If so how?

<
2条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 01:41

    Structs can be passed by reference using the inout keyword and the & operator.

    struct Test {
        var val1:Int
        let val2:String
    
        init(v1: Int, v2: String) {
            val1 = v1
            val2 = v2
        }
    }
    
    var myTest = Test(v1: 42, v2: "fred")
    
    func change(test: inout Test) {
        // you can mutate "var" members of the struct
        test.val1 = 24
    
        // or replace the struct entirely
        test = Test(v1: 10, v2: "joe")
    }
    change(test: &myTest)
    myTest // shows val1=10, val2=joe in the playground
    

    This practice is discouraged unless you can prove it's the only way to get the performance you need in a critical situation.

    Note that you won't save the burden of copying the UIImage by doing this. When you put a reference type as a member of a struct, you still only copy the reference when you pass it by value. You are not copying the contents of the image.

    Another important thing to know about struct performance is copy-on-write. Many built in types like Array are value types, and yet they're very performant. When you pass around a struct in Swift, you don't undergo the burden of copying it until you mutate it.

    Check out the WWDC video on value types to learn more.

提交回复
热议问题