0

I have code like this

let index = tableView.selectedRowIndexes.map { Int($0) }
        arrDomains.remove(at: index)

But got error:

Cannot convert value of type '[Int]' to expected argument type 'Int'

How convert [Int] to int?

Swift 4, macOS

Gereon
  • 17,258
  • 4
  • 42
  • 73
Marina
  • 44
  • 6
  • 2
    That depends on the result you're expecting. You have an array of the selected _rows_. Do you only care about the first selected row or perhaps the last selected row? Alternatively, maybe it would be better to enumerate all the selected rows and remove all of them. – David Rönnqvist Oct 18 '18 at 12:32
  • @DavidRönnqvist Thanks for attention. You are right it would be better to get all the selected lines and delete them. But I do not really understand how to do it. – Marina Oct 18 '18 at 12:37

2 Answers2

5

Indexes is plural that means there are multiple values

selectedRowIndexes returns an IndexSet object. You could use forEach but you have to reverse the indexes otherwise you get the famous mutating-while-iterating-out-of-range error.

let indexes = tableView.selectedRowIndexes
indexes.reversed().forEach{ arrDomains.remove(at: $0) }

Mapping the indexSet to [Int] is redundant.

Here is an optimized remove(at indexes: IndexSet) method.

vadian
  • 274,689
  • 30
  • 353
  • 361
1

index is array of Int. But you need to pass Int to the remove method.

If you want to remove all objects for selected row indexes, than write:

let indexes = tableView.selectedRowIndexes.map { Int($0) }
indexes.reversed().forEach { arrDomains.remove(at: $0) }

If you want to remove object at some index, than write:

guard let index = tableView.selectedRowIndexes.map { Int($0) }.first(where: { /*.your condition here */ }) else { return }
arrDomains.remove(at: $0)
Ilya Kharabet
  • 4,203
  • 3
  • 15
  • 29