如何从结构体嵌套数组下的结构体修改键的值。我从stackoverflow中找到了一种可能的解决方案,但它只适用于一个级别。我想知道是否有更好的解决方案?如果键是可选的呢?
struct Article {
var id: Int
var book: [Book]
}
struct Book {
var page: Int
var author: [Author]
}
struct Author {
var visited: Bool
}
// update value of visited key in nested array of struct
var a = Article(id: 1, book: [Book(page: 11, author: [Author(visited: true)])])
print(a)
a.book.modifyElement(atIndex: 0) {$0.author.modifyElement( atIndex: 0) {$0.visited = false}}
print(a)
更改数组中struct的值
“如何从struct数组嵌套下的struct中修改属性
的值”。尝试这种方法,这是一种比您现有的更好更紧凑的解决方案:
var a = Article(id: 1, book: [Book(page: 11, author: [Author(visited: true)])])
print("\n---> before a: \(a)")
a.book[0].author[0].visited = false // <-- here
print("\n---> after a: \(a)")