0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Basic Operators - Arithmetic Operator

Posted at

Swift はすべての数値型で利用できる4つの標準的な 算術演算子 arithmetic operators を備えている。

  • 加算 (+)
  • 減算 (-)
  • 乗算 (*)
  • 割算 (/)
let addition = 1 + 2 // 3が格納される
let subtract = 5 - 3 // 2が格納される
let multiply = 2 * 3 // 6が格納される
let division = 10.0 / 2.5 // 4.0が格納される

C言語やObjective-Cと異なり、Swiftの算術演算子は標準ではオーバーフローを許容しない。意図的に行う方法については Overflow Operators を参照すること。

また、加算演算子は文字列接続にも利用できる。

let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName
// fullName は "John Doe" になる。

余剰演算子

余剰演算子 remainder operator (a % b) は割り算の余りを求める演算子。

let remainder = 9 % 4
// 9 / 4 の余りは 1 なので、remainder の値は 1 になる。

余剰演算子は a % b の答えを求めるにあたり処理の背景では下記のような計算を行なっている。

a = (b * 乗数) + 余り

ここでの乗数は、a にあてはまる b の最大倍数がそれとなる。
9 と 4 をあてて言うと、

9 = (4 * 2) + 1

となる。
また、余剰演算子は値が負であっても同じく機能する。

let negativeRemainder = -9 % 4
// negativeRemainder は -1 となる。

先ほどの式に -9 と 4 をあてはめると、

-9 = (4 * -2) + -1

となる。

単項マイナス演算子

数値の前に - を添えて利用する。その値の正負を反転させる。

let three = 3
let minusThree = -three
// minusThree は -3
let plusThree = -minusThree
// plusThree は 3

単項プラス演算子

数値の前に + を添えて利用する。これは対象の数値を一切変更せずにそのまま返す。

let minusSix = -6
let alsoMinusSix = +minusSix
// alsoMinusSix は -6

単項プラス演算子は実質何もしない演算子ではあるが、数値を負に変換するために単項マイナス演算子を使うコードにおいて正の数値を表すのに有用となる。

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?