我有一个要保存到UserDefaults的结构。这是我的结构
struct Song { var title: String var artist: String } var songs: [Song] = [ Song(title: "Title 1", artist "Artist 1"), Song(title: "Title 2", artist "Artist 2"), Song(title: "Title 3", artist "Artist 3"), ]
在另一个ViewController中,我有一个UIButton附加到此结构,例如
@IBAction func likeButtonPressed(_ sender: Any) { songs.append(Song(title: songs[thisSong].title, artist: songs[thisSong].artist)) }
我想要它,以便每当用户单击该按钮时,它也将结构保存到UserDefaults,以便每当用户退出该应用程序然后将其打开时,它都会被保存。我该怎么做?
在Swift 4中,这几乎是微不足道的。只需将其标记为采用Codable协议,即可使其结构可编码:
struct Song:Codable { var title: String var artist: String }
现在让我们从一些数据开始:
var songs: [Song] = [ Song(title: "Title 1", artist: "Artist 1"), Song(title: "Title 2", artist: "Artist 2"), Song(title: "Title 3", artist: "Artist 3"), ]
这是将其添加到UserDefaults中的方法:
UserDefaults.standard.set(try? PropertyListEncoder().encode(songs), forKey:"songs")
以下是如何再次将其取回的方法:
if let data = UserDefaults.standard.value(forKey:"songs") as? Data { let songs2 = try? PropertyListDecoder().decode(Array<Song>.self, from: data) }