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]()
3
  • 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. Commented Feb 13, 2020 at 17:32
  • ah thank you! do you happen to know how to copy an array? Commented Feb 13, 2020 at 17:36
  • @LouisaScheinost What do you mean, "copy" an array? They are already passed by value. Commented Feb 13, 2020 at 17:40

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.