Xcode
Swift
UserDefaults
Swift3.0
Xcode8

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

More than 1 year has passed since last update.

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

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

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