G
G
GOODDUDE2017-07-06 17:58:25
iOS
GOODDUDE, 2017-07-06 17:58:25

Initializer for conditional binding must have Optional type, not 'Any'?

I have an array in which I store names of users. When trying to display the names in the tableViewCell, an error occurs -

Initializer for conditional binding must have Optional type, not 'Any'

Here is my code
var usersIn = [] as NSMutableArray
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    let userList = usersIn[indexPath.row]

    if let username = userList {
        cell.textLabel?.text! = username as! String
    }

    return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}

It seems to me when I run this line
if let username = userList {
        cell.textLabel?.text! = username as! String
    }
an error occurs.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
ManWithBear, 2017-07-06
@GOODDUDE

Why do you need NSMutableArray there at all? You shoot yourself in the foot.

var usersIn: [String] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = usersIn[indexPath.row]
    return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question