LoginSignup
0
1

More than 3 years have passed since last update.

【swift】 Class vs Struct: Choose Structures by Default ~構造体を通常は使ってください~

Last updated at Posted at 2019-08-15

私は趣味で iOS アプリを作っています。
最近 Swift 5.1 の公式ドキュメントに
Choosing Between Structures and Classes(原文)
構造体かクラスのいずれかを選ぶ(対訳)
という項目があるのを見つけました。

Choose Structures by Default
構造体を通常は使ってください
Using structures makes it easier to reason about a portion of your code without needing to consider the whole state of your app. Because structures are value types—unlike classes—local changes to a structure aren't visible to the rest of your app unless you intentionally communicate those changes as part of the flow of your app. As a result, you can look at a section of code and be more confident that changes to instances in that section will be made explicitly, rather than being made invisibly from a tangentially related function call.
構造体を使うことは、あなたのアプリの全体の状態を考える必要なしに、あなたのコードの一部について結論を下すことを簡単にします。構造体が値型であることから — クラスとは違い — 構造体への局所的変更はあなたのアプリの残りには不可視です、あなたが意図的にそれら変更をあなたのアプリのフローの一部として伝達しない限りは。結果として、あなたはコードのある区画を調べて、その区画のインスタンスに対する変更が明確だということを、ほとんど無関係な関連する関数呼び出しから不可視に行われるよりむしろずっと自信を持てます。
Important
重要
Treat identity with care. Sharing class instances pervasively throughout an app makes logic errors more likely. You might not anticipate the consequences of changing a heavily shared instance, so it's more work to write such code correctly.
同一性を注意して取り扱ってください。アプリの隅々まで行き渡る共有クラスインスタンスは、論理エラーをより招きやすくします。あなたは、重く共有されるインスタンスの変更の帰着を見越して備えられないかもしれません、それでそのようなコードを正しく書くためにさらに仕事が増えます。

私はオブジェクト指向の概念もよく分かっていないアマ・プログラマーですが、class や struct の使い分けについて勉強中に上記の記事を見つけました。(BASIC 上がりの手続き型プログラマーなので、カスタム class や struct を定義するような高度なプログラムは書いたことがありません・・・。)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1