1
sojingle 2014-06-07 00:00:35 +08:00
“A value type is a type that is copied when it is assigned to a variable or constant, or when it is passed to a function.
You’ve actually been using value types extensively throughout the previous chapters. In fact, all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, and are implemented as structures behind the scenes.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/cn/jEUH0.l Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries 这些都是值类型... |
2
txx 2014-06-07 00:02:57 +08:00
請看 wwdc 402就知道了 struct 是個 value not ref每次都是 copy 的
|
3
gluttony 2014-06-07 00:03:51 +08:00
The Swift Programming Language 明确说明了数组的这种行为:
If you assign an Array instance to a constant or variable, or pass an Array instance as an argument to a function or method call, the contents of the array are not copied at the point that the assignment or call takes place. Instead, both arrays share the same sequence of element values. When you modify an element value through one array, the result is observable through the other. For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. This includes appending, inserting, or removing items, or using a ranged subscript to replace a range of items in the array. If and when array copying does take place, the copy behavior for an array’s contents is the same as for a dictionary’s keys and values, as described in Assignment and Copy Behavior for Dictionaries. https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_109 |
4
exoticknight 2014-06-07 00:04:47 +08:00
如果需要ref怎么办……
|
5
yelite 2014-06-07 00:07:05 +08:00
var b = a
这个时候 b 和 a 是不同的 array,只是 array 内部指向的数据是同样的? |
6
limon OP 多谢楼上几位,刚才看到Collection,Class部分还没读,现在明白了。Array是值传递,但是估计为了减少copy,只有在改变长度的时候才做copy的动作,所以一开始下标访问还是指向同一个地方,不过这个行为不知道真的要中招。。。
|
7
limon OP 另外,我发现不光是改变长度才会copy,用range改变内容也会copy,即使长度没变。
|
8
limon OP @exoticknight 我也在想这个,先慢慢往下读。。。
|
9
ultragtx 2014-06-07 01:51:58 +08:00
可以继续用NSMutableArray/NSArray
|
10
Livid MOD Python 的是这样的:
>>> a = [1,2] >>> b = a >>> a[0] = 0 >>> a [0, 2] >>> b [0, 2] >>> a.append(3) >>> a [0, 2, 3] >>> b [0, 2, 3] |
11
manfay 2014-06-07 08:47:20 +08:00 1
一直觉得Python真是把这些细节整理得很清晰,所有变量全是reference,所有数组、字典、函数甚至数字都是object,因此不管变量a指向什么类型,b = a 之后,b is a就为True。
|
14
limon OP @Livid 嗯,其他语言都没这种特性。 我觉得这个设计并不好,可能重构的时候修改了前面的代码影响了后面的赋值。
|
15
lxfxf 2014-06-07 10:06:40 +08:00
书里面讲的很清楚...unshare,或者copy过去。如果不是改变数组长度的操作,都是reference。
|
17
leedstyh 2014-06-07 22:21:13 +08:00
Go也是这样,你了解了底层实现后,就知道这不是坑了
|