简体   繁体   English

Swift将数组中的随机元素返回到文本中

[英]Swift return random element from array into text

This problem which I know should be very easy has stumped me for hours.这个我知道应该很容易的问题让我难住了好几个小时。

I try to get a random element from a simple Array into a Text in SwiftUI but i get errors I don't understand, the recent error I got was:我尝试从一个简单的Array获取一个随机元素到SwiftUI一个Text中,但是我得到了我不明白的错误,我最近得到的错误是:

Instance method 'appendInterpolation' requires that '[Result]' conform to '_FormatSpecifiable'实例方法“appendInterpolation”要求“[Result]”符合“_FormatSpecifiable”

What would be the simplest way to implement this?实现这一点的最简单方法是什么? I understand this has been answered many times but I am too bad at coding to understand when I try to google it.我知道这已经被多次回答,但是当我尝试用谷歌搜索它时,我编码太差而无法理解。

struct Result: Identifiable {
    var id = UUID()
    var score: Int
}

struct ContentView: View {

    @State private var showDetails = false

    @State var results = [Result(score: 8),
                          Result(score: 5),
                          Result(score: 10)]


    var body: some View {
        VStack {
            Button(action: {   
                self.results.randomElement()
            }) {
                Text("Button title, \(results)")
            }

        }
    }
}

Since results aren't changing, there's no need for @State (coupled with an initializer on Result so we can easily map a list of scores).由于results不会改变,因此不需要@State (与Result上的初始值@State相结合,因此我们可以轻松地映射分数列表)。 Instead, we want to introduce a new variable to hold a random Result and mark that as a state.取而代之的是,我们要引入一个新的变量来保存随机Result和标志作为一个国家。 So each time we press the button, we set a new random result and trigger a view update.所以每次我们按下按钮时,我们都会设置一个新的随机结果并触发视图更新。

Please note that I have marked the var as optional (since I do not know the logic behind any initial value) and displaying a 0 if this thing is nil (probably not what you want in your final code - you can decide whatever default value, or conditional view display, makes sense for you)请注意,我已将 var 标记为可选(因为我不知道任何初始值背后的逻辑)并在此内容nil显示0 (可能不是您在最终代码中想要的 - 您可以决定任何默认值,或条件视图显示,对您有意义)

struct Result: Identifiable {
    var id = UUID()
    var score: Int
    init(_ score: Int) {
        self.score = score
    }
}

struct ContentView: View {

    @State private var showDetails = false

    let results = [8, 5, 10].map(Result.init)

    @State var randomResult: Result?

    var body: some View {
        VStack {
            Button(action: {   
                self.randomResult = self.results.randomElement()
            }) {
                Text("Button title, \(randomResult?.score ?? 0)")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM