Marina
Marina

Reputation: 44

How convert [Int] to int?

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

Upvotes: 0

Views: 119

Answers (2)

vadian
vadian

Reputation: 285270

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.

Upvotes: 5

Ilya Kharabet
Ilya Kharabet

Reputation: 4631

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)

Upvotes: 1

Related Questions