-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

2
  • Why did you not include func modifyElement…? Why is book not books and author not authors? Commented Oct 25, 2022 at 23:18
  • have you tried this: a.book[0].author[0].visited = false, works for me. Commented Oct 25, 2022 at 23:21

1 Answer 1

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)")
Sign up to request clarification or add additional context in comments.

4 Comments

thinking about a more dynamic way to do it. but this one works
what do you mean a more dynamic way? What is that?
lets say I need to modify the value under different path of key in different struct i do not want to write something likea.book[0].author[0].visited x.book.author.x.y[0].z = ""
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.