Skip to content

Instantly share code, notes, and snippets.

@enomoto
Created July 17, 2018 07:03
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save enomoto/629a85bd4e82902057c0b614602a71b3 to your computer and use it in GitHub Desktop.
Save enomoto/629a85bd4e82902057c0b614602a71b3 to your computer and use it in GitHub Desktop.
save array of struct to UserDefaults
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")]
@theriseof9
Copy link

wow thanks

@elhajjajiamine
Copy link

Thank you so much 😊

@boonyawat
Copy link

Thank you, Thank you, Thank you! The best solution. Easy to understand and easy to use.

@dinoali
Copy link

dinoali commented Feb 9, 2023

Thanks @enomoto ,
Your answer really helped me to achieve my final goal, can you tell me how can I delete a specific index in the array?

@PonomarevOleg
Copy link

Omg, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment