0

I have the following code. When it runs, it triggers the error : Cannot subscript a value of type '[String : Int]' with an index of type 'String?'

Can someone please help

self.books = self.books.filter { $0.completed[MUser.sharedInstance.getUserId()] ?? 0 > 0 }

completed is declared as

var completed = [String : Int]()
Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • 1
    `getUserId()` is obviously an optional. The error says the key must be non-optional. Basically it's the same issue as in your [previous question](https://stackoverflow.com/questions/60196762/value-of-type-book-has-no-member-append). – vadian Feb 13 '20 at 17:32
  • ah thank you! do you happen to know how to copy an array? – Chris Hansen Feb 13 '20 at 17:36
  • @LouisaScheinost What do you mean, "copy" an array? They are already [passed by value](https://stackoverflow.com/q/373419/9607863). – George Feb 13 '20 at 17:40

1 Answers1

1

The error indicates, that MUser.sharedInstance.getUserId() returns an optional.
You need to unwrap this:

self.books = self.books.filter {  
  guard let userID = MUser.sharedInstance.getUserId() else { return false }
  return $0.completed[userID] ?? 0 > 0 
}
Robin Schmidt
  • 1,153
  • 8
  • 15