Vinicius Silvestre Vinicius Silvestre - 3 months ago 17
Swift Question

store data in a class array in swift

I'm trying to learn swift on my own, but I have hit a small wall, what am I missing here?

https://i.stack.imgur.com/WmZUu.png

import Foundation

class aluno
{
var cpf: String?
var notaP1: Double = 0.0
var notaP2: Double = 0.0
var notaFinalAluno: Double = 0.0
}

var condiçaoLoop = 1
var count = 0

func verificaNota()
{
while condiçaoLoop != 0
{
print("Digite o cpf do aluno")
let cpfAluno = readLine()
print("Digite a nota da P1 do aluno")
let notaP1Aluno = Double(readLine()!)
print("Digite a nota da P2 do aluno")
let notaP2Aluno = Double(readLine()!)

let notaFinalAluno = (notaP1Aluno! + notaP2Aluno!)/2

if notaFinalAluno >= 7
{
print("Aluno aprovado com média: \(notaFinalAluno)")
print("Deseja verificar mais algum aluno? 1 Sim 0 Não")
let resposta = Int(readLine()!)
if resposta == 0
{
condiçaoLoop = 0
}
}
else
{
print("Aluno de final com média: \(notaFinalAluno)")
print("Deseja verificar mais algum aluno? 1 Sim 0 Não")
let resposta = Int(readLine()!)
if resposta == 0
{
condiçaoLoop = 0
}
}
count += 1
}
for i in 1...count
{
var notasAlunos: [aluno] = []
notasAlunos.cpf[i] = cpfAluno
notasAlunos.notaP1[i] = notaP1Aluno!
notasAlunos.notaP2[i] = notaP2Aluno!
notasAlunos.notaFinalAluno[i] = notaFinalAluno
}
}
verificaNota()


what im trying to do is get two grades from the user, calculate its final score and then store the data in an array

Answer Source

All of the constants that you define inside your while loop have no scope outside the loop. They exist inside the loop but not outside it. Define cpfAluno etc, before (outside) the while loop so that they are available inside the for in loop.

    func verificaNota()
    {
       var cpfAluno = 0.0
       var notaP1Aluno = 0.0
       var notaP2Aluno = 0.0
       var notaFinalAluno = 0.0

       while condiçaoLoop != 0
       {
          print("Digite o cpf do aluno")
          cpfAluno = readLine()
          print("Digite a nota da P1 do aluno")
          notaP1Aluno = Double(readLine()!)
          print("Digite a nota da P2 do aluno")
          notaP2Aluno = Double(readLine()!)

          notaFinalAluno = (notaP1Aluno! + notaP2Aluno!)/2