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

SOLVED: Updating objects in array of objects

Forums > SwiftUI

nodes.n_array[index].x and nodes.n_array[index].y are not updating. Circles stay at starting points even when dragging.

import SwiftUI

struct ContentView: View {
    @StateObject var nodes = Nodes()

    var body: some View {

        ZStack {   
            ForEach(0..<nodes.n_array.count) { index in
                nodes.n_array[index].drawShape()
                    .gesture(DragGesture()
                        .onChanged { value in
                            nodes.n_array[index].x = value.translation.width
                            nodes.n_array[index].y = value.translation.height
                        }
                        .onEnded { value in

                        }
                    )
            }
        }
    }
}
import Foundation
import SwiftUI

class Node: ObservableObject, Decodable {
    enum CodingKeys: CodingKey {
        case id, x, y, text, red, green, blue, shape
    }

    public let id: Int
    @Published var x: Double
    @Published var y: Double
    public let text: String
    public var red: Double
    public var green: Double
    public var blue: Double
    public var shape: Int

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        x = try container.decode(Double.self, forKey: .x)
        y = try container.decode(Double.self, forKey: .y)
        text = try container.decode(String.self, forKey: .text)
        red = try container.decode(Double.self, forKey: .red)
        green = try container.decode(Double.self, forKey: .green)
        blue = try container.decode(Double.self, forKey: .blue)
        shape = try container.decode(Int.self, forKey: .shape)
    }
}

extension Node {
    func circle() -> some View {
        Circle()
            .fill(Color(red: red, green: green, blue: blue))
            .frame(width: 64, height: 64, alignment: .center)
            .position(x: x, y: y)
    }

    func square() -> some View {
        Rectangle()
            .fill(Color(red: red, green: green, blue: blue))
            .frame(width: 64, height: 64, alignment: .center)
            .position(x: x, y: y)
    }

    @ViewBuilder func drawShape() -> some View {
        switch shape{
        case 1: circle()
        case 2: square()
            default: Text("Failed")
        }
    }
}

Class with array of nodes:

import Foundation

class Nodes: ObservableObject {
   @Published var n_array = [Node]()

    init() {
        let url = Bundle.main.url(forResource: "nodes", withExtension: "json")!
        let data = try! Data(contentsOf: url)
        n_array = try! JSONDecoder().decode([Node].self, from: data)
    }
}

3      

You Node object is a class, which is a reference type. SwiftUI prefers to work with value types.

This is an issue because changing the value of a property of a class object doesn't change the object, so SwiftUI can't observe the change. Changing a value type creates a whole new item and destroys the old one, so SwiftUI sees the change and can update the View accordingly.

You should rework your code so that Node is a struct. I would also suggest using an enum instead of an Int for Node.shape. And instead of ForEach(0..<nodes.n_array.count) you should make Node conform to Identifiable and then loop through nodes.n_array directly rather than by index.

3      

Here's how I changed your code to make it work. Note that since I didn't have your nodes.json file, I stripped out the Codable stuff and just build Nodes from a memberwise initializer. I also didn't implement Node.shape as an enum, leaving that as an exercise for the future.

import SwiftUI

struct ContentView: View {
    @StateObject var nodes = Nodes()

    var body: some View {

        ZStack {
            ForEach($nodes.n_array) { $node in
                node.drawShape()
                    .gesture(
                        DragGesture()
                            .onChanged { value in
                                node.x = value.location.x
                                node.y = value.location.y
                            }
                            .onEnded { value in

                            }
                    )
            }
        }
    }
}

struct Node: Identifiable {
    enum CodingKeys: CodingKey {
        case id, x, y, text, red, green, blue, shape
    }

    public let id: Int
    public var x: Double
    public var y: Double
    public let text: String
    public var red: Double
    public var green: Double
    public var blue: Double
    public var shape: Int
}

extension Node {
    func circle() -> some View {
        Circle()
            .fill(Color(red: red, green: green, blue: blue))
            .frame(width: 64, height: 64, alignment: .center)
            .position(x: x, y: y)
    }

    func square() -> some View {
        Rectangle()
            .fill(Color(red: red, green: green, blue: blue))
            .frame(width: 64, height: 64, alignment: .center)
            .position(x: x, y: y)
    }

    @ViewBuilder func drawShape() -> some View {
        switch shape {
        case 1: circle()
        case 2: square()
        default: Text("Failed")
        }
    }
}

class Nodes: ObservableObject {
    @Published var n_array = [Node]()

    init() {
        n_array = [
            Node(id: 1, x: 100, y: 100, text: "Hello", red: 0, green: 1, blue: 0, shape: 1),
            Node(id: 2, x: 200, y: 400, text: "Goodbye", red: 1, green: 0, blue: 1, shape: 2),
        ]
    }
}

3      

Thank you so much man. I really appreciate your help.

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.