カウントアプリ
import UIKit class ViewController: UIViewController { var count = 0 @IBOutlet weak var countLabel: UILabel! @IBAction func countButton(sender: AnyObject) { count = count + 1 countLabel.text = String(count) } @IBAction func resetButton(sender: AnyObject) { countLabel.text = "0" } }
ポイント ・classの中にcount変数を用意する。 ・countButtonを押したときに、count変数に+1する。 ・countLabelに表示するために、countLabel.textにcount変数を代入する。その際に、countLabel.textはString型しか代入できないため、String(count)でString型に型変換する。
countを0にするresetButtonはcountLabel.textに文字列0を代入することで、リセットする。 なぜ文字列に変換するのか?前述した通り、countLabelは文字列しか扱うことができないため。
しかし、ここで問題が起こる。 ・countLabelに文字列が入っていた場合、カウントされない。→if文を使うことで回避する。 ・0にリセットしても0を表示しているだけなので、変数countはそのまま。例えば5までカウントしてリセットすると、いったん0と表示されるが、再度countButtonを押すと、6からカウントされる。 そのため、以下のようにコードを修正する。
import UIKit class ViewController: UIViewController { @IBOutlet weak var countLabel: UILabel! @IBAction func counterButton(sender: UIButton) { // if let countText = countLabel.text { if let count = Int(countText) { countLabel.text = String(count + 1) }else { countLabel.text = "0" } } //以下のコードでも同様に動作する // if let countText = countLabel.text, count = Int(countText) { // // countLabel.text = String(count + 1) // // } else { // // countLabel.text = "0" // // } } @IBAction func resetButton(sender: UIButton) { countLabel.text = "0" } }
条件1:定数countTextにcountLabel.textを代入する。(これは基本的にどんな数、文字をいれても通るはず) 条件2:定数countにcountTextをInteger型に変換し代入する→Integer型に代入できた場合、countLabel.textに定数countに+1をしてString型に変換し代入する(countLabel.textはString型でないと代入できない) Integer型に変換できなかった場合、elseにいく。つまり、countLabelに文字列String型が入っていた場合、countLabel.textに文字列0が代入される。