This question already has answers here:
Simple swift array append not working
(3个答案)
去年关门了。
这是我的代码:
import UIKit

struct StructName{
    var name: String?
    var specs: [Spec]?

    init(specs: [Spec]? = nil, name: String? = nil) {
        self.specs = specs
        self.name = name
    }

}

struct Spec{
    var name: String
    var title: String
    var content: String
    var display: Bool
}

class ViewController: UIViewController {
    var structNames: [StructName] = []
    var specs = [Spec]()

    override func viewDidLoad() {
        super.viewDidLoad()
            specs.append(Spec(name: "Name_1", title: "Title_1", content: "Content_1", display: false))
            structNames.append(StructName(name: "Name_3"))
            structNames.append(StructName(name: "Name_4"))
            structNames.append(StructName(name: "Name_1"))

            append()
            print(structNames)
    }


    func append(){
        for i in specs{
            let index = structNames.index { (structName) -> Bool in
                structName.name == i.name
            }
            print(structNames[index!].name)

            structNames[index!].specs?.append(Spec(name: "a", title: "a", content: "a", display: false))
        }
    }


}

为什么这不起作用?
        structNames[index!].specs?.append(Spec(name: "a", title: "a", content: "a", display: false))

它应该打印这个:
[测试实用程序(实用程序名称:可选(“名称3”),规格:无),测试实用程序(实用程序名称:可选(“名称4”),规格:无),测试实用程序(实用程序名称:可选(“名称1”),规格:追加规格一])]
如您所知,我想将给定规范附加到特定索引。

最佳答案

您永远不会将每个specsStructName属性初始化为nil以外的任何值。因此,当您引用structNames[index!].specs时,specsnil并且可选链接跳过对append的调用。
一种解决方案是将specs初始化为空数组,而不是nil

struct StructName{
    var name: String?
    var specs: [Spec]

    init(specs: [Spec] = [], name: String? = nil) {
        self.specs = specs
        self.name = name
    }
}

仅供参考-您真的想要一个可选的name

10-08 08:20