Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

Remover do array de selecionados

Vi que para pegar a posição de um elemento no array o find nao esta mais funcionando, então botei assim:

            if let position = selecionados.indexOf(items[indexPath.row]) {
                selecionados.removeAtIndex(position)
            }

Mas ainda esta dando o erro: " cannot convert value type "item" to expected argument type '@noescape(Item) throws->Bool'

Como corrijo ?

Minha classe toda abaixo


protocol AddMealDelegate {
    func add(meal:Meal)
}


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    @IBOutlet var nameField: UITextField!;
    @IBOutlet var happinessField: UITextField!;
    var delegate:AddMealDelegate?

    var items = [Item(name: "Eggplant Brownie", calories: 10),
                 Item(name:"Zucchini Muffin", calories: 10),
                 Item(name:"cookie", calories: 10),
                 Item(name:"Coconut oil", calories:500),
                 Item(name:"Chocolate Frosting", calories: 1000),
                 Item(name:"Chocolate Chip", calories: 1000)]

    var selecionados = Array<Item>()

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let row = indexPath.row
        let item = items[row]

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
        cell.textLabel?.text = item.name

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        let item = items[indexPath.row]

        if cell == nil{
            return
        }

        if cell!.accessoryType == UITableViewCellAccessoryType.None {
            cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
            selecionados.append(item)

            print("Nome: \(item.name)")
        }else{
             cell!.accessoryType = UITableViewCellAccessoryType.None
            if let position = selecionados.indexOf(items[indexPath.row]) {
                selecionados.removeAtIndex(position)
            }

        }


    }

    @IBAction func add(){

        if nameField == nil || happinessField == nil {

            return
        }

        let name = nameField.text!;
        let happiness = Int(happinessField.text!)

        if happiness == nil {

            print("insira o happiness")
            return
        }


        let meal = Meal(name: name, happiness: happiness!)

        print("Meal: \(meal.name) \(meal.happiness)");

        if delegate == nil {
            print("Erro no delegate")
            return
        }

        delegate!.add(meal);

        if let navigation = self.navigationController{
            navigation.popViewControllerAnimated(true)
        }

    }


}
4 respostas
solução!

Resolvi, tinha que botar o Equatable e implementar o metodo == na classe Item.

Olá Alexandre, também passei por esta mesma situação. Me parece que no swift II, o find foi deprecado em razão do indexOf, que ainda exige o Equatable na classe, bem como implementar a função ==.

Boa dica pessoal.

Fazendo o uso do func find(elements: Array<Item>, toFind: Item) -> Int? na chamada do método let position = find(selected, items[indexPath.row]) o compilador estava me obrigando a inserir o toFind let position = find(selected, toFind: items[indexPath.row]) porque, segundo ele, estava perdendo o label do argumento toFind na chamada.

Com o selected.indexOf(items[indexPath.row]) ficou muito mais claro a intenção e o compilador não reclamou.

Abraço.

No Swift 3 mudou um pouco mais e agora ficou:

 if let position = selected.index(of: item) {
      selected.remove(at: position)
 }

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software