如何更改整数数组中的元素?

huangapple go评论65阅读模式
英文:

How do you change an element in an integer array?

问题

我在尝试更改整数数组中元素的值时遇到了问题。
我收到了错误消息“类型'()'无法符合'View'”。

我非常沮丧。我可以引用特定元素而不会出现任何错误!

Import SwiftUI

struct ContentView: View {
var someInts:[Int] = [10, 20, 30]
var body: some View {
  // 没有错误

  Text(String(someInts[1]))
  // 下面的行生成错误???

  someInts[1] = 16
}
英文:

I am having trouble changing the value of an element in an integer array.
I am getting the error Type'()'cannot conform to 'View'.

I am very frustrated. I can reference the specific element without any error!

Import SwiftUI

struct ContentView: View {
var someInts:[Int] = [10, 20, 30]
var body: some view {
  // no error

  Text(String(someInts[1]))
  // line below generates an error????

  someInts[1] = 16
}

答案1

得分: 1

您没有返回一个 View

大多数 Swift 视图将是一个(通常是链接的)单个表达式,因此具有隐式的 return 语句。如果您在 View 结构中包含其他表达式,那么您需要明确返回视图。

这意味着您需要这样做:

struct ContentView: View {
    var someInts: [Int] = [10, 20, 30]
    var body: some View {
        let textView = Text(String(someInts[1]))
        someInts[1] = 16
        return textView
    }
}

然而,这仍然不会起作用,因为该结构是不可变的。您需要将任何数据持久保存在 View 结构之外,或者使用 @State(或其他持久状态的)属性包装器来允许您进行更改。

struct ContentView: View {
    @State var someInts: [Int] = [10, 20, 30]
}

尽管这将编译通过,但仍然没有太多意义,因为您将显示文本,然后修改底层数据,这将强制视图立即更新。您可能会考虑直接使用该值初始化数组,以避免闪烁!

英文:

You are not returning a View

Most swift views will be a (often chained) single expression, and so have an implicit return statement. If you are including other expressions inside the View struct then you will need to explicitly return the view.

This implies you need to do this:

struct ContentView: View {
var someInts:[Int] = [10, 20, 30]
var body: some view {
  let textView = Text(String(someInts[1]))
  someInts[1] = 16
  return textView
}

However this still won't work as the struct is immutable. You need to persist any data outside of the View struct or use the @State (or other state-persisting) property wrapper to allow you to mutate it.

struct ContentView: View {
   @State var someInts:[Int] = [10, 20, 30]

While this will compile, it still makes little sense as you will display the text, then modify the underlying data, which will force the view to immediately update. You might just as well initialise the array with the value and avoid the flicker!

huangapple
  • 本文由 发表于 2023年6月9日 03:00:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定