错误消息:“函数声明了一个不透明的返回类型,但是在其主体中没有用于从其推断基础类型的返回语句”

问题描述

我正在开发一个简单的琐事应用程序,最终您将选择两个问题之一。到目前为止,我有一些变量和数组可以使我掌握关于正确和错误的信息。我有一些错误,我无法确定任何帮助?我正在使用SwiftUI,但我真的很新。

问题是我的vstack给了我这样的消息:“'vstack'初始化程序的结果未使用”

我的View给我这个错误:“函数声明了一个不透明的返回类型,但是在其主体中没有用于从其推断基础类型的返回语句”

这是我的代码

import SwiftUI

struct ContentView: View {
    
    @State var currentNum = 0
    var person = ["Michael Jackson","Elton John","Prince"]
    var dead = [1,1]
    // 1 = yes 0 = no
    @State var correct = true
    
    var body: some View {
        vstack{
        Text(person[currentNum])
            
            Button(action: {
                
            },label: {
                Text("Dead")
            })
            
            
            
        }
        
        func checkDead() {
            if dead[currentNum] == 1{
                return correct = true
            }
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

谢谢-NM

解决方法

return关键字是必需的,并且需要更早地移动嵌套函数。

var body: some View {
  func checkDead() {
    if dead[currentNum] == 1 {
      return correct = true
    }
  }

  return VStack {
,

只需将功能checkDeadbody中移出

var body: some View {
    VStack {
        Text(person[currentNum])
        Button(action: {
            
        },label: {
            Text("Dead")
        })
    }
}

func checkDead() {
    if dead[currentNum] == 1{
        return correct = true
    }
}
,
var body: some View {
        VStack{
        Text(person[currentNum])
            
            Button(action: {
                
            },label: {
                Text("Dead")
            })
            
            
            
        }
        
// Problem Starts! :
        func checkDead() {
            if dead[currentNum] == 1{
                return correct = true
            }
        }
// Problem Ends!
        
    }

您要在变量内声明一个函数(在变量checkDead中声明一个函数body

长话短说,不要那样做!在类的范围内而不是在主体中声明函数:
struct ContentView: View {
    
    @State var currentNum = 0
    var person = ["Michael Jackson","Elton John","Prince"]
    var dead = [1,1]
    // 1 = yes 0 = no
    @State var correct = true
    
    var body: some View {
        VStack{
        Text(person[currentNum])
            
            Button(action: {
                
            },label: {
                Text("Dead")
            })
            
            
            
        }
        
        // func checkDead() {
        //    if dead[currentNum] == 1{
        //        return correct = true
        //    }
        //}
        // move it to the struct's scope and outside the variable `body`
    }

//here is where it should be
 func checkDead() {
            if dead[currentNum] == 1{
                correct = true
            }
        }

}