不能对不可变值使用可变成员:'parent' 是一个 'let' 常量?

Cannot use mutating member on immutable value: 'parent' is a 'let' constant?

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)

当你传递一个结构(按值复制)时,你不能在没有 inout 的情况下改变函数参数。

修改你的代码并重试:

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

如果您想通过 nils,您还必须进行此更改:

var nilParent: FianceItem? = nil
var root = FianceItem.createType(name: "MyRoot", parent:&nilParent)