为什么不能将元素附加到结构上?

时间:2018-09-10 17:39:32

标签: arrays swift struct

这是我的代码:

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

它应打印以下内容:

  

[test.Utility(实用程序名称:可选(“ Name_3”),规格:无),test.Utility(实用程序名称:可选(“ Name_4”),规格:无),test.Utility(实用程序名称:可选(“ Name_1 “),规格:“我添加了SPEC”)]

您可能会理解,我想将给定的Spec附加到特定索引。

1 个答案:

答案 0 :(得分:2)

您绝不会将每个specs的{​​{1}}属性初始化为StructName以外的任何其他属性。因此,当您引用nil时,structNames[index!].specsspecs,并且可选的链接会跳过对nil的调用。

一种解决方案是将append初始化为空数组,而不是specs

nil

仅供参考-您真的要一个可选的struct StructName{ var name: String? var specs: [Spec] init(specs: [Spec] = [], name: String? = nil) { self.specs = specs self.name = name } } 吗?