英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论