UserDefaultsを使って永続化してみる Swift3.0

 

コピペ要員として、書き残しておこうと思います

import UIKit

var jayZsongNameResult : String?

class ViewController: UIViewController {

    //構造体に永続化した値を入れておく
    struct artist {
        enum jayZ : String {
            case jayZsongName
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //最初はnil
        print(UserDefaults.standard.string(forKey: artist.jayZ.jayZsongName.rawValue) as Any)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func save(_ sender: Any) {

        //永続化実行
        let jayZsongName = "4:44"
        UserDefaults.standard.set(jayZsongName, forKey: artist.jayZ.jayZsongName.rawValue)
        jayZsongNameResult = UserDefaults.standard.string(forKey: artist.jayZ.jayZsongName.rawValue)!
    }
}

ソース

GitHub

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事