Created
July 17, 2018 07:03
-
-
Save enomoto/629a85bd4e82902057c0b614602a71b3 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")] |
Thank you so much 😊
Thank you, Thank you, Thank you! The best solution. Easy to understand and easy to use.
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?
Omg, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wow thanks