问题描述
我有一个我要保存到UserDefaults的结构。这是我的结构
I have a struct that I want to save to UserDefaults. Here's my struct
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,如
In another ViewController, I have a UIButton that appends to this struct like
@IBAction func likeButtonPressed(_ sender: Any) {
songs.append(Song(title: songs[thisSong].title, artist: songs[thisSong].artist))
}
我想要它,这样每当用户点击该按钮时,它也会将结构保存到UserDefaults,以便每当用户退出应用程序然后打开它时,它就会被保存。我该怎么做?
I want it so that whenever the user clicks on that button also, it saves the struct to UserDefaults so that whenever the user quits the app and then opens it agian, it is saved. How would I do this?
推荐答案
在Swift 4中,这几乎是微不足道的。只需将其标记为采用Codable协议即可使您的结构可编码:
In Swift 4 this is pretty much trivial. Make your struct codable simply by marking it as adopting the Codable protocol:
struct Song:Codable {
var title: String
var artist: String
}
现在让我们从一些数据开始:
Now let's start with some data:
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:
Here's how to get that into UserDefaults:
UserDefaults.standard.set(try? PropertyListEncoder().encode(songs), forKey:"songs")
以下是如何让它再次退出:
And here's how to get it back out again later:
if let data = UserDefaults.standard.value(forKey:"songs") as? Data {
let songs2 = try? PropertyListDecoder().decode(Array<Song>.self, from: data)
}
这篇关于将Struct保存到UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!