Cannot call 'append' using an argument list of type '(String ?!)'

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

The error I am getting is: Can't call 'append' with an argument list like '(String ?!)'

What am I doing wrong?

var usernames = [""]

func updateUsers() {      
    var query = PFUser.query()
    query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
    var fetchedUsers = query!.findObjects()

    for fetchedUser in fetchedUsers! {
        self.usernames.append(fetchedUser.username)
    }
}

      

+2


source to share


2 answers


I solved my problem. I declare the array as an empty array and expand the optional code with the following code:



var usernames = [String]()

self.usernames.removeAll(keepCapacity: true)

    for fetchedUser in fetchedUsers! {
        if let username = fetchedUser.username as String! {
            self.usernames.append(username)
        }
    }

      

+2


source


PFUser.username

is optional and you cannot add an option to an array String

in Swift. This is because an optional parameter can be nil

, and a String array in Swift only accepts strings.

You need to either force expand the optional, or use the 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, since NRKirby mentions in the comments to your question, you might want to look at array initialization usernames

differently. Currently the first element is an empty string.

0


source







All Articles