2016-12-23 4 views
0

私は、私はその後、私はIntegerReferenceを含む配列firstIntegersそして葯配列secondIntegersisを割り当てるだけで今firstIntegersスウィフトアレイの動作

var firstIntegers = [IntegerReference(), IntegerReference()] 
var secondIntegers = firstIntegers 

の参照を代入している。この

class IntegerReference { 
    var value = 10 
} 

ように見える一つのクラス を作成しましたfirstIntegersの値を変更したい

firstIntegers[0].value = 100 
print(firstIntegers[0].value) //100 it is ok.. 
print(secondIntegers[0].value) //100 it is ok.. 

しかし、私はfirstIntegers配列を変更したい場合には、IntegerReferenceは、クラス(例えば、1であるので、あなたがfirstIntegersで値を変更secondIntegers変更の値である理由secondIntegers配列

firstIntegers[0] = IntegerReference() 
print(firstIntegers[0].value) //10 it is ok.. 
print(secondIntegers[0].value) // 100 Why 100? it should be 10 or Not? 
+3

朝早すぎる:p。とにかく、 'secondIntegers'が最初の値(' 100')のインスタンスをまだ持っているからです。 'firstIntegers [0] = IntegerReference()'では、単に 'firstIntegers'のインスタンスを置き換えただけですが、' secondIntegers'はまだ影響を受けません。インスタンスの値を変更するのは、 'Array'と何か関係があるのではなく、' class'だからです。 – Eendje

+0

私は同様の答えを持っていましたが、@Eendjeは非常にうまく答えました:P – C0mrade

+1

[構造と列挙は値の型です](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ ClassesAndStructures.html) – vadian

答えて

2

理由には影響しません)。

firstIntegersでインスタンスを置き換えた瞬間、IntegerReferenceという新しいインスタンスがfirstIntegersに配置されます。しかし、100の値を持つ古いインスタンスはまだsecondIntegersの中にあるため、アクセスされたときにはまだ100が出力されます(例2)。

私が何を意味するかを示すために、インスタンスのアドレスを含むいくつかの例を作成しました。

データ:

class Foo { 
    var value = 10 
} 

var array1 = [Foo(), Foo()] 
var array2 = array1 

例1:

array1[0].value = 100 

print("address:", getAddress(array1[0]), "value:", array1[0].value) 
print("address:", getAddress(array2[0]), "value:", array2[0].value) 

出力:

アドレス:0x000060000002d820値:100
アドレス:0x000060000002d820値:100

例2:

array1[0] = Foo() 

print("address:", getAddress(array1[0]), "value:", array1[0].value) 
print("address:", getAddress(array2[0]), "value:", array2[0].value) 

出力:

アドレス:0x000060800002c120値:10
アドレス:0x000060000002d820値:100

編集:

であなたは私がどのようにして住所を知っているのだろうか:

func getAddress(_ object: AnyObject) -> UnsafeMutableRawPointer { 
    return Unmanaged.passUnretained(object).toOpaque() 
} 
+0

'getAddress()'の定義を追加したい場合があります。標準ライブラリの一部ではありません。 –

+0

そうですが、主なポイントはアドレスを表示することだと思ったので、わかりやすくするためにその部分を残しました。 – Eendje