WWDC22 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!

   

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))

   

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?

   

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.

   

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.

   

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.

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.