WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

What is an append equivalent for a struct?

Forums > Swift

Hello,

Tortoises:

class Tortoises: ObservableObject {
    @Published var items = [Tortoise]()
    }

say I have this array:

struct Tortoise: Equatable, Codable, Hashable {

    var hibernations = [Hibernation]()
    var name: String
    var age: Int

    }

and a hibernation struct

struct Hibernation: Equatable, Hashable, Codable {
    var name: String
    var startDate: Date
    var endDate: Date
    }

aswell as an add view here:

struct AddHibernationView: View {
    @Environment(\.presentationMode) var presentationMode

    @ObservedObject var tortoises: Tortoises

    @State private var name = ""
    @State private var involved = ""

    @State private var startDate = Date()
    @State private var endDate = Date()

    @State private var showEnd = false

    @State private var length = 0

    @State private var Index = 0

    var disabled: Bool{
        if (name.isEmpty){
            return true
        }
        return false
    }

    var body: some View{
        ZStack{
            Color(.gray)
                .ignoresSafeArea()
            VStack{
                Form{
                    Section{
                        TextField("Name of Hibernation", text: $name)
                        Picker("Involved Tortoise", selection: $involved){
                            ForEach(tortoises.items, id: \.name){ item in
                                Text(item.name)
                            }
                        }
                    }
                    Section{
                        DatePicker("Start Date:", selection: $startDate, displayedComponents: .date)

                        Toggle("Hibernation Ended", isOn: $showEnd.animation())

                        if (showEnd){
                            DatePicker("End Date", selection: $endDate, displayedComponents: .date)
                        }
                    }
                }.cornerRadius(30)
                .padding(60)

                }

How would I add elements to the hibernations Array in the Tortoise struct? preferably from all of the variables the addview changes?

Thankyou in advance!

2      

Since hibernations is an array of Hibernation items, you just create a new Hibernation and call hibernations.append(_:).

let newHibernation = Hibernation(name: name, startDate: startDate, endDate: endDate)
hibernations.append(newHibernation)

You can even combine the two operations:

hibernations.append(Hibernation(name: name, startDate: startDate, endDate: endDate))

2      

Hello @roosterboy this is my fault there actually isn't an @ObservedObject var hibernations: Hibernations it is just using the hibernation variable inside of Tortoise, how would I do it now?

2      

He might, we all might, have an issue solving this as you've not provided the definition of the Tortoises class.

Off the top of my head, I'd think you should pull all your AddTurtle(named: "Yertle") code inside your Tortoise class.

In general you should keep all your business logic for adding, updating, and removing tortoises in one class.

2      

Edited. I originally had a seperate hibernations class but I want to make each tortoise have it's own array of Hibernations so i can have them in different for each loops depending on what tortoise is doing the Hibernation.

2      

Zebs updated his post showing a sparse Tortoises class with one published var, an array of Tortoise objects he's calling items. By the way, in a peer code review my team might report that items is a terrible name for a collection of Tortoise objects! Apparently a group of Tortoises is called a Creep. Check it out.

class Tortoises: ObservableObject {
    @Published var creep = [Tortoise]()  // collection of tortoises is called a creep, per the never wrong interweb.

    // You probably have some business rules about adding new Tortoise objects to this array.
    // Think about those rules and create some private funcs in this class.

    // However you should consider one PUBLIC func to allow a programmer to add a new Tortoise to the creep array.
    public addTortoise( newTortoise: Tortoise) {
        // lots of validation logic
        creep.append( newTortoise )
}

Likewise in your Tortoise struct, consider adding a public method allowing a progammer to add a new Hibernation object to the Tortoise's array of hibernations.

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.