LoginSignup
76
36

[Swift] FunctionとComputed Propertyの使い分けの基準

Last updated at Posted at 2016-09-10

Swiftでプログラミングをしていると、引数なしのFunctionを使うかComputed Propertyを使うかで迷う時があります。

その判断基準がKotlinのコーディング規約にあったので引用します。

Kotlin: Coding Conventions

Functions vs properties
In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.

Prefer a property over a function when the underlying algorithm:

  • does not throw
  • is cheap to calculate (or cached on the first run)
  • returns the same result over invocations if the object state hasn't changed

以下の条件に当てはまる場合は、functionよりpropertyを使う方がよい。

  • 例外を投げない
  • 計算量が少ない(または初回実行時にキャッシュされる)。
  • オブジェクトの状態が変化していない場合、何度呼び出しても同じ結果を返す。

補足

コメントで教えて頂きましたが、Swift API Design Guidelinesにも以下の記述がありました。

https://swift.org/documentation/api-design-guidelines/#general-conventions

  • Document the complexity of any computed property that is not O(1). People often assume that property access involves no significant computation, because they have stored properties as a mental model. Be sure to alert them when that assumption may be violated.

(O(1)ではないcomputed propertyではその旨をドキュメント(コメント)に明記すること。 プロパティアクセスは一般的に計算コストが安価だと見なされるので、そうでない場合はその旨の明記が必要である。)

参考

76
36
1

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
76
36