-2
import UIKit
import SwiftUI

var str = "Hello, playground"

struct FianceItem: Identifiable,Codable {
    
    public var id: UUID
    public var type: String
    public var order: Int32
    public var parentID: UUID?
    public var childs:[FianceItem]
    
    static func createType(name: String, parent: FianceItem?) -> FianceItem {
        var item = FianceItem(id: UUID(), type:name, order: 1, parentID: nil,childs: [])
        
        if parent != nil {
            item.parentID=parent!.id
            
            //Error Cannot use mutating member on immutable value: 'parent' is a 'let' constant
            parent?.childs.append(item)
        }
        return item
    }
    
}


var root = FianceItem.createType(name: "MyRoot", parent: nil)
var child = FianceItem.createType(name: "child", parent: root)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
jeryycnlong
  • 131
  • 1
  • 5
  • And the question is...? – matt Feb 23 '21 at 05:18
  • Seems that the child array in the parent is declared as a let variable. Which means that the array is inmutable, and you can’t modify their values. If you declare the childs variable of the parent as a var instead of let, you should be able to add more elements into the array. – Jacobo Feb 23 '21 at 05:18
  • Although for the error I see that the parent is not mutable. Seems that you declare it as let, instead of var. those keywords define the mutability of a variable. – Jacobo Feb 23 '21 at 05:20

1 Answers1

0

As you are passing a struct (copies by value), you can't mutate function parameters without an inout.

Edit your code to this and try again:

static func createType(name: String, parent: inout FianceItem?) -> FianceItem {

You will also have to do this change if you want to pass nils:

var nilParent: FianceItem? = nil
var root = FianceItem.createType(name: "MyRoot", parent:&nilParent)
Daniel Ryan
  • 6,976
  • 5
  • 45
  • 62