Cannot invoke 'append' with an argument list of type '(String?!)'

前端 未结 2 1829
傲寒
傲寒 2021-01-21 10:51

I\'m trying to add usernames from Parse in an array to display them in a UITableView, but get an error when I\'m appending the usernames to my array.

The error I get is:

2条回答
  •  感动是毒
    2021-01-21 11:22

    PFUser.username is an optional, and you can't append an optional into a String array in Swift. This is because the optional can be nil, and a String array in Swift only accepts strings.

    You need to either force unwrap the optional, or use if-let syntax to add it if it exists.

    Force Unwrap

    self.usernames.append(fetchedUser.username! as String)
    

    Or if-let

    if let name = fetchedUser.username as? String {
      self.usernames.append(name)
    }
    

    Plus as NRKirby mentions in the comments on your question, you might want to look at initialising the usernames array differently. At the moment the first element is an empty string.

提交回复
热议问题