2
2

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.

Property の挙動がよくわからないけど、これ仕様なのかよくわからん

Posted at

よくわからない挙動。

オブジェクトのプロパティの値を見て、挙動を変えたいこんな感じのコード。

/** swift property atomic test */

class Test {
	var isRunning:Bool?

	init() {
		isRunning = false
	}

	func toggle() -> Bool {
		if isRunning {
			println("Run")
			isRunning = false
		} else {
			println("Stop")
			isRunning = true
		}
		return true
	}
}

var Tes = Test()

println("isRunning => \(Tes.isRunning) == wanna false") // wanna false
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna true") // wanna true
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna false") // wanna false


実行

$ ./prop
isRunning => false == wanna false
Run
isRunning => false == wanna true
Run
isRunning => false == wanna false

期待としては isRunning の値の変化で Stop => Run となって欲しかったけど、実際は二回とも Run => Run になっている。

推察からした対処コード

おそらく、 var isRunning:Bool? としたので値があるかないかだけを見たのじゃないか、と思い下記のコードを実行

/** swift property atomic test */

class Test {
	var isRunning:Bool!

	init() {
		isRunning = false
	}

	func toggle() -> Bool {
		if isRunning {
			println("Run")
			isRunning = false
		} else {
			println("Stop")
			isRunning = true
		}
		return true
	}
}

var Tes = Test()

println("isRunning => \(Tes.isRunning) == wanna false") // wanna false
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna true") // wanna true
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna false") // wanna false

実行

$ ./prop
isRunning => false == wanna false
Run
isRunning => false == wanna true
Run
isRunning => false == wanna false

期待通り動きませんでした

実際に期待通り動いた対処コード

/** swift property atomic test */

class Test {
	var isRunning:Bool?

	init() {
		isRunning = false
	}

	func toggle() -> Bool {
		if isRunning == true {
			println("Run")
			isRunning = false
		} else {
			println("Stop")
			isRunning = true
		}
		return true
	}
}

var Tes = Test()

println("isRunning => \(Tes.isRunning) == wanna false") // wanna false
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna true") // wanna true
Tes.toggle()
println("isRunning => \(Tes.isRunning) == wanna false") // wanna false

実行

$ ./prop
isRunning => false == wanna false
Stop
isRunning => true == wanna true
Run
isRunning => false == wanna false

ちゃんと比較演算子を指定すれば、 Stop => Run となった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?