UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to access variables inside a struct inside a class

Forums > Swift

Hello, I can only figure out how to access the struct inside the class, not the variables inside the struct.

struct Introduction: View {
    @StateObject var variable = Variable()
    @StateObject var tempVars = tempVariables()
    var body: some View {
        Button("Ok"){
        }
        Button("Don't show Again"){

        }
    }
}

I would like to get the varibales inside the struct in the buttons

The class:

class Variable: ObservableObject {
    @Published var items = [Variables]() {
        didSet {
            if let encoded = try? JSONEncoder().encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() {
        if let savedItems = UserDefaults.standard.data(forKey: "Items") {
            if let decodedItems = try? JSONDecoder().decode([Variables].self, from: savedItems) {
                items = decodedItems
                return
            }
        }

        items = []
    }
}

The Struct:

struct Variables: Identifiable, Codable {
    var id = UUID()
    let allTime: Double
    let introduction: Bool
}

struct Temporary {
    let closeIntro: Bool
}

3      

variable.items[0].id doesn't work? Where the zero should match the id you want to read from.

3      

variable.items gives you access to the array in the Variable class. Then you can access each item using subscript notation: variable.items[0], variable.items[1], etc. Then you can access the properties of each item using dot notation: variable.items[0].allTime, etc.

I don't see in the code you've posted where Temporary is used, but I am going to assume tempVars.temporary is perhaps what you are looking for. At any rate, it follows the same pattern as what I mentioned above for variable.items.

3      

@roosterboy

What does the number do?

3      

It's the index into your array of items. The first item in the array is index 0, the second item is index 1, etc.

3      

@roosterboy

So introduction in the variables struct would be 3 because i am getting a fatal error that says it is out of range.

3      

Your Variable class contains a property called items that is an array of Variables structs.

The variable property in the View named Introduction is an instance of the Variable class, meaning it has a property called items that is an array of Variables structs.

Each item in an array has an index, starting at 0 for the first item. So the first Variables struct inside the items array of the variable property can be accessed as variable.items[0].

Once you have that item, you can then access its properties: id, allTime or introduction.

So you essentially have this structure:

Variable
    |- items
        |- 0: Variables
            |- id
            |- allTime
            |- introduction
        |- 1: Variables
            |- id
            |- allTime
            |- introduction
        |- etc etc

Clear?

Okay, so let's say you want to show a Text element that displays the introduction property of the first item in the items array. Here's how you would do that:

struct Introduction: View {
    @StateObject var variable = Variable()
    @StateObject var tempVars = tempVariables()
    var body: some View {
        Text(variable.items[0].introduction) //remember, arrays start at index 0
    }
}

If you wanted to show the introduction from the 2nd item in the array, you would use Text(variable.items[1].introduction). If you wanted to show the value of allTime from the 1st item in the array, you would use Text(variable.items[0].allTime), and so on.

You are getting an out of index error when calling variable.items[3] because you apparently don't have 4 (remember indexes are 0-based!) items in the array.

I would strongly suggest renaming your data structures and variables to make it clearer what things are and how they are to be used. Variable and variable just are not very descriptive names. You will end up reading your code far more than you write it, so it is always a good idea to name things so that they will be understandable to you when you come back to read something you wrote before. Also so that other people reading your code can understand it better.

So, for instance, Variable. What does that mean in the context of this data structure? It contains ann array called items; maybe something like ItemStore would be a better name than Variable. Even that is a too generic, but I don't know your codebase like you do so it's hard to suggest something more specific.

It's also confusing when you have a class called Variable and a struct called Variables. I had to go back and edit this answer because I got confused which was which. Plus, in Swift, the convention is to name a data type in the singular and then name an array of those types as a plural. So you would have a class called, e.g., ThingStore, a struct called Thing and a variable holding an array of Things called things. (But don't actually use Thing, etc. That's just as bad as Variable. I just wanted to demonstrate the pattern.)

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.