Swift 是按值传递还是按引用传递
我对 Swift 真的很陌生,我刚刚读到类是通过引用传递的,并且数组/字符串等被复制.
I'm really new to Swift and I just read that classes are passed by reference and arrays/strings etc. are copied.
通过引用传递与在 Objective-C 或 Java 中实际传递a"引用的方式相同还是正确传递引用?
Is the pass by reference the same way as in Objective-C or Java wherein you actually pass "a" reference or is it proper pass by reference?
Swift 中的事物类型
规则是:
类实例是引用类型(即你对类实例的引用实际上是一个指针)
Class instances are reference types (i.e. your reference to a class instance is effectively a pointer)
函数是引用类型
其他一切都是值类型;其他一切"仅表示结构实例和枚举实例,因为这就是 Swift 中的全部内容.例如,数组和字符串是结构体实例.正如 newacct 指出的那样,您可以通过使用 inout
并获取地址来传递对其中一个事物的引用(作为函数参数).但是类型本身就是值类型.
Everything else is a value type; "everything else" simply means instances of structs and instances of enums, because that's all there is in Swift. Arrays and strings are struct instances, for example. You can pass a reference to one of those things (as a function argument) by using inout
and taking the address, as newacct has pointed out. But the type is itself a value type.
引用类型对象在实践中很特殊,因为:
A reference type object is special in practice because:
仅仅赋值或传递给函数就可以产生对同一个对象的多个引用
Mere assignment or passing to function can yield multiple references to the same object
对象本身是可变的,即使对它的引用是一个常量(let
,无论是显式的还是隐式的).
The object itself is mutable even if the reference to it is a constant (let
, either explicit or implied).
对对象的更改会影响该对象,正如对它的所有引用所见.
A mutation to the object affects that object as seen by all references to it.
那些可能是危险的,所以要小心.另一方面,传递引用类型显然是高效的,因为只复制和传递一个指针,这是微不足道的.
Those can be dangers, so keep an eye out. On the other hand, passing a reference type is clearly efficient because only a pointer is copied and passed, which is trivial.
显然,传递值类型是更安全的",而 let
的意思是它所说的:您不能通过 let
引用来改变结构实例或枚举实例.另一方面,安全性是通过制作单独的值副本来实现的,不是吗?这不会使传递值类型的成本变得昂贵吗?
Clearly, passing a value type is "safer", and let
means what it says: you can't mutate a struct instance or enum instance through a let
reference. On the other hand, that safety is achieved by making a separate copy of the value, isn't it? Doesn't that make passing a value type potentially expensive?
嗯,是和不是.它并不像你想象的那么糟糕.正如 Nate Cook 所说,传递值类型并不必然意味着复制,因为 let
(显式或隐式)保证了不变性,因此不需要复制任何东西.甚至传递到 var
引用并不意味着东西将被复制,只是它们在必要时可以被复制(因为有一个突变).文档特别建议您不要弄乱内裤.
Well, yes and no. It isn't as bad as you might think. As Nate Cook has said, passing a value type does not necessarily imply copying, because let
(explicit or implied) guarantees immutability so there's no need to copy anything. And even passing into a var
reference doesn't mean that things will be copied, only that they can be if necessary (because there's a mutation). The docs specifically advise you not to get your knickers in a twist.