7
1

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 3 years have passed since last update.

`if (a == 1 && a == 2 && a == 3)` は真か?

Posted at

背景

なんだか面白そうな記事を見つけた
(a == 1 && a == 2 && a == 3)は真と評価できますか?
のでSwiftでやってみた

コード

var b = 0

var a: Int {
    get {
        b += 1
        return b
    }
}

if (a == 1 && a == 2 && a == 3) {
    print("Complete!")
}

解説

aとは別で変数を用意(ここではb)して、aのgetterでbをインクリメントし、bをreturnする。
if文でaを3回取得するが、その度にaのgetterを通るため、取得されるaの値は1ずつ増えていく。

結果

できた。👏
スクリーンショット 2020-06-01 14.53.36.png

まとめ

getterを使うと、if文の中で同じ変数でも、異なる値を取得できる😳

p.s. 他にいい方法があれば教えてください!

7
1
4

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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?