-2

How to modify the value of key from struct that is under nested of array of struct. I found one of possible solution from stackoverflow but it is only for one level. I am wondering if there is any better solution? and what if the key is optional?

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)

Changing The value of struct in an array

jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

1

"How to modify the value of property from struct that is under nested of array of struct". Try this approach, a better more compact solution than what you have:

 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)")
  • thinking about a more dynamic way to do it. but this one works – jacobcan118 Oct 27 '22 at 18:24
  • what do you mean `a more dynamic way`? What is that? – workingdog support Ukraine Oct 27 '22 at 22:58
  • lets say I need to modify the value under different path of key in different struct i do not want to write something like```a.book[0].author[0].visited x.book.author.x.y[0].z = ""``` – jacobcan118 Oct 28 '22 at 06:35
  • 1
    I think, no matter how you skin the cat, eventually you need to determine which book you want to change, which author you want to change and which property you want to change. If you want to change a range of books and/or authors, then you can use a for loop. You can wrap some of these steps into pre-canned functions, but that's just more code to do something simple. – workingdog support Ukraine Oct 28 '22 at 06:57