swift - 将值设置为不断变化的默认值
问题描述
我正在创建一个游戏,其中我有一个高分值,即使我退出应用程序,每次更新时我都想保存它。我已经有了 highscore 的值,它每次更新 score > highscore 但如果我退出应用程序,highscore 将重置为 0,我希望它保持不变。
导入 SwiftUI
struct Europe: View {
@State private var countries = ["Albania", "etc."].shuffled()
@State private var corrrectAnswer = Int.random(in: 0...5)
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var userScore = 0
@State private var highScore = 0
var body: some View {
ZStack{
LinearGradient(gradient: Gradient(colors: [.white,.blue]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
VStack(spacing:30){
VStack{
Text("Tap the flag of")
.foregroundColor(.black)
.fontWeight(.black)
Text(countries[corrrectAnswer])
.foregroundColor(.black)
.font(.largeTitle)
.fontWeight(.black)
}
VStack(spacing:50){
HStack(spacing:40) {
VStack(spacing:40) {
ForEach(0..<3){ number in
Button(action: {
self.flagTapped(number)
self.highScoreSet(number)
}){
Image(self.countries[number])
.resizable()
.frame(width: 130, height: 100)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black,lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
}
VStack(spacing:40) {
ForEach(4..<7){ number in
Button(action: {
self.flagTapped(number)
self.highScoreSet(number)
}){
Image(self.countries[number])
.resizable()
.frame(width: 130, height: 100)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black,lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
}
}
VStack{
Text("Score: \(userScore)")
.foregroundColor(.white)
.fontWeight(.black)
.font(.subheadline)
Text("High Score: \(highScore)")
.foregroundColor(.white)
.fontWeight(.black)
.font(.subheadline)
}
Spacer()
}
}
}
.alert(isPresented: $showingScore){
Alert(title: Text(scoreTitle), message: Text("Your score is \(userScore)"), dismissButton: .default(Text("Continue")){
self.askQuestion()})
}
}
func highScoreSet(_ number: Int){
if highScore < userScore {
highScore = userScore
}
}
func flagTapped(_ number: Int){
if number == corrrectAnswer{
scoreTitle = "Right"
userScore += 1
}
else {
scoreTitle = "Wrong!\n Thats the flag of \(countries[corrrectAnswer])"
userScore = 0
}
showingScore = true
}
func askQuestion(){
countries.shuffle()
corrrectAnswer = Int.random(in: 0...5)
}
}
struct Europe_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
解决方案
您可以使用@AppStorage
属性包装器。关于如何使用它的好文章。
改变:
@State private var highScore = 0
至:
@AppStorage("high_score") private var highScore = 0
推荐阅读
- apache-spark - 由于 PySpark 时间戳,将 Spark 数据帧保存到 Azure Synapse 时出现问题
- java - 保存父对象时,防止休眠自动删除@Transient子对象
- amazon-web-services - 如何允许 kubernetes 中的单个 serviceaccount 使用来自不同集群的角色?
- tensorflow - 在多个音频帧上训练 CNN
- vim - 是否可以将特定标签文件添加到 vim 中的特定窗口/缓冲区?
- django - 有没有办法在开发过程中在移动设备上加载 django 网站?
- azure-api-management - API Management + App Gateway 用于托管面向 Internet 的 API 的用例
- swiftui - SwiftUI Negative Padding Z 顺序
- c++ - 如何使用旧的 stdlib 和 libc 在旧的 linux 发行版中构建 C++17 应用程序?
- flutter - 因此,firebase_core ^0.7.0 与 cloud_firestore ^0.14.0 不兼容