[英]Appending struct onto Struct Array in Swift 3
我有一個結構:
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'類型的不可變值上使用變異成員
如何更改需要轉換的值?
您最初創建的數組不正確。
更改:
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"))
您可以使用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 {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.