【问题标题】:Appending struct onto Struct Array in Swift 3在 Swift 3 中将结构附加到结构数组上
【发布时间】:2018-05-21 00:52:16
【问题描述】:

我有一个结构:

struct Note{
    var date: String;
    var comment: String;
}

然后我创建一个数组,其中嵌套了两个数组,

var data = [[Note()],[Contributors()]]

这两个数组用于填充表格视图的两个部分。 我需要将一个结构附加到 Notes 结构数组中,但是当我尝试使用

附加它时
data[0].append(Note(date: "06-06-2012",comment:"Created Note"))

(data[0] as! Note).append(Note(date: "06-06-2012",comment:"Created Note"))

抛出错误

不能对'Note'类型的不可变值使用变异成员

如何改变需要强制转换的值?

【问题讨论】:

  • 您不需要附加新的Note AND Contributors(基于我的测试)-data.append([Note(data: "06-06-2012",comment:"Created Note"), [Contributors()]] 或类似的东西

标签: arrays swift struct


【解决方案1】:

您最初创建的数组不正确。

变化:

var data = [[Note()],[Contributors()]]

到:

var data: [Any] = [[Note](),[Contributors]()]

您的代码创建了一个数组,该数组在索引 0 处包含一个 Any 数组,其中包含一个空的 Note 实例,在索引 1 处包含一个 Any 数组,其中包含一个空的 Contributors 实例。

此修复程序创建一个数组,该数组在索引 0 处包含一个空 Note 数组,在索引 1 处包含一个空 Contributors 数组。

但即使有所有这些“修复”,如果你这样做,你仍然会收到错误:

(data[0] as! Note).append(Note(date: "06-06-2012",comment:"Created Note"))

data 包含两种不同类型的数据有点奇怪。你真的应该有两个数组:

var notes = [Note]()
var contributors = [Contributors]()

那么你就可以轻松做到了:

notes.append(Note(date: "06-06-2012",comment:"Created Note"))

【讨论】:

    【解决方案2】:

    您可以使用protocol获得解决方案

    protocol DataSourceNoteContributors {}
    
    struct Contributors: DataSourceNoteContributors{
    
    }
    struct Note:DataSourceNoteContributors{
        var date: String;
        var comment: String;
    }
    

    然后就可以轻松使用了

        var data = [Note(date: "date", comment: "comment"),Contributors()]
    
        data.append(Note(date: "note1", comment: "comment2"))
        data.append(Contributors())
    

    // 使用强制转换识别

    if data[0] as Note {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多