Use Userdueflts on a struct

My code below uses a struct to organize the data. However when I go to the next view controller and return to the original one all of the data is deleted. How can I use user defaults to save the data to the label.

             import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
    @IBOutlet var label: UILabel!
    var contacts = [Person]()
    @IBAction func save(_ sender: Any) {
        contacts.append(Person(name: a.text!,  phone: Int(c.text!)!))
        let sortedContacts = contacts.sorted {
            ($, $ < ($, $
        label.text = contacts.count == 0 ? "" : {$0.description}.joined(separator: "\n")

    struct Person {
        var name: String
        var phone: Int
        static var myStruct = [String]();
        var description: String {
            return   "\(name),\(phone)"

Hi @timswift,
There are a couple of options for you, you can save the data into a DB or persist to a text file or when you present the new viewController ensure that the UI elements are not released.

It is not a very good idea to store data in the UI elements like UILabel, etc.

Lastly, code helps to see what you are doing



This topic was automatically closed after 166 days. New replies are no longer allowed.