Swift通过引用传递结构? [英] Swift pass struct by reference?

查看:128
本文介绍了Swift通过引用传递结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过类似的问题,但我没有看到我满意的答案。

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?

下面是一个代码作为例子的参考:

Here is a code as a reference for examples:

struct MyData {
    var contentId: Int = 0
    var authorId: Int = 0
    var image: UIImage = UIImage(named: "myimage")
}

正如您所看到的,我这样做的主要原因是因为没有让我的图像遍布整个地方。

As you see my main reason of doing this is because not having my image multiplying all over the place.

推荐答案

可以使用 inout 关键字和<$来通过引用传递结构c $ c>& operator。

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.

注意你不会通过这样做来节省复制UIImage的负担。将引用类型作为结构的成员放置时,仍然只能在按值传递时复制引用。您没有复制图像的内容。

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.

关于结构性能的另一个重要事项是写时复制。像Array这样的许多内置类型都是值类型,但它们非常高效。当你在Swift中传递一个结构时,你不会承担复制它的负担,直到你改变它为止。

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.

检查关于价值类型的WWDC视频了解更多信息。

这篇关于Swift通过引用传递结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆