self.userDefaults.object(forKey: “load”) != nil で、空判定
let userDefaults = UserDefaults.standard var load = 0 var str:String = "連勝" @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var resultView: UILabel! @IBOutlet weak var imageView2: UIImageView! @IBOutlet weak var gameResult: UILabel! @IBAction func getGoo(_ sender: Any) { let results1 = ["Image1","Image2","Image3"] let random1 = arc4random_uniform(UInt32(results1.count)) let image1 = UIImage(named: results1[Int(random1)]) imageView.image = image1 let image4 = UIImage(named: "Image4") imageView2.image = image4 let even = "あいこ" let win = "あなたの勝ち" let lose = "あなたの負け" if random1 == 0 { self.gameResult.text = even if self.userDefaults.object(forKey: "load") != nil { self.load = self.userDefaults.integer(forKey: "load") } else { self.load = 0 } } else if(random1 == 1){ self.gameResult.text = win if self.userDefaults.object(forKey: "load") != nil { self.load = self.userDefaults.integer(forKey:"load") self.load += 1 } else { self.load = 1 } } else { self.gameResult.text = lose if self.userDefaults.object(forKey: "load") != nil { self.load = self.userDefaults.integer(forKey:"load") self.load -= 1 } else { self.load = -1 } } self.gameResult.text = String(self.load) + str UserDefaults.standard.set(self.load, forKey: "load") }
なるほど、保存できることはわかった。
負けた時に、-1連勝となるので、var str:String = “連勝” の他に、連敗のテキストを作り、連勝中の負けの時と連敗中の勝ちの時は、load = 0 にリセットですな。
勝ちの時
if self.userDefaults.object(forKey: "load") != nil { if self.userDefaults.integer(forKey:"load") > 0 { self.load = self.userDefaults.integer(forKey:"load") self.load += 1 } else { self.load = 0 }
負けの時
if self.userDefaults.integer(forKey:”load”) < 0 { self.load = self.userDefaults.integer(forKey:"load") self.load -= 1 } else { self.load = 0 } [/code]