C と同様に、Swift には代入演算子 (=) と別の演算子を組み合わせた複合代入演算子があります。この例は、加算代入演算子 (+=) です。

var a = 1
a += 2
// a は 3

a += 2 は a = a + 2 の簡略表現です。加算と代入のタスクを同時に実行する演算子として組み合わされています。

NOTE
複合代入演算子は、値を返しません。例えば、let b = a += 2 のように書くことはできません。これは、上で述べたインクリメント・デクリメント演算子とは異なる動作となります。

複合代入演算子の全リストを、Expressions で確認することができます。


Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.