Forked from enomoto/UserDefaultsAndStructArray.swift
Created
November 8, 2022 05:46
-
-
Save youn9k/1c9c1ab8891ac25eea58958745786051 to your computer and use it in GitHub Desktop.
save array of struct to UserDefaults
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Book: Codable { | |
let title: String | |
let author: String | |
} | |
let KeyForUserDefaults = "myKey" | |
func save(_ books: [Book]) { | |
let data = books.map { try? JSONEncoder().encode($0) } | |
UserDefaults.standard.set(data, forKey: KeyForUserDefaults) | |
} | |
func load() -> [Book] { | |
guard let encodedData = UserDefaults.standard.array(forKey: KeyForUserDefaults) as? [Data] else { | |
return [] | |
} | |
return encodedData.map { try! JSONDecoder().decode(Book.self, from: $0) } | |
} | |
save([Book(title: "The Great Gatsby", author: "Fitzgerald"), | |
Book(title: "Ulysses", author: "Joyce")]) | |
let books = load() | |
print(books) //[Book(title: "The Great Gatsby", author: "Fitzgerald"), Book(title: "Ulysses", author: "Joyce")] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment