darkenney
darkenney

Reputation: 37

swiftui, beginner - don't put logic in views

I know this doesn't work (Cannot find 'notes' in scope) - the whole views are for display and not for logic, but I'm not finding a beginner, beginner explanation for how to construct this correctly. I'm not even sure what to search on - anyone have a solid place to start for a beginner? (This is a much stripped down example and w/o - state and binding - which does make sense for me.) Thanks.

    let grade = "F"
    var body: some View {
        NavigationView{
            VStack{ Text("Final grade: \(grade)")
                NavigationLink{
                    deets(grade: grade)
                } label: {
                    Text("See Notes")
                }
            }
        }
    }
}

struct deets: View {
    var grade: String
    var body: some View {
        if (grade == "F") {
            let notes = "Please see me"
            }
        else { let notes = "you passed"}
            Text("\(notes)")
            }
        } 

Upvotes: 1

Views: 521

Answers (1)

vadian
vadian

Reputation: 285079

The recommended way for this task is the ternary operator

struct Deets: View {
    let grade: String

    var body: some View {
        Text(grade == "F" ? "Please see me" : "you passed")
    }
}

If the expression evaluates to true the portion after the question mark is displayed otherwise the portion after the colon.

And please name structs always with a starting capital letter.

A good source to learn SwiftUI is 100 days of SwiftUI

Upvotes: 3

Related Questions