J. Doe
J. Doe

Reputation: 13103

Get element from array by reference

I have an array filled with structs. Let's say I want to change the first element of the array it if exists. I expected that something like this works:

if var first = &unconfirmedDataFromSocket.first {
    first.markAsResend() // some mutating func
}

But I get this error:

Use of extraneous '&'

Is it possible in Swift to do what I want? Ofcourse there is an ugly workaround:

  1. Remove the &
  2. After calling markAsResend, remove the first element of the array and add the first variable

But I was hoping for something more nicer.

Upvotes: 0

Views: 155

Answers (1)

David Pasztor
David Pasztor

Reputation: 54775

You need to subscript the array by index to be able to mutate its elements directly. To ensure that the index is actually valid, you can use indices.contains or for the 1st element specifically, you can simply check that isEmpty is false.

if !unconfirmedDataFromSocket.isEmpty {
    unconfirmedDataFromSocket[0].markAsRead()
}

Or using indices (this works for elements other than the 1st as well):

let index = 0
if unconfirmedDataFromSocket.indices.contains(index) {
    unconfirmedDataFromSocket[index].markAsRead()
}

Upvotes: 2

Related Questions