0

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.

2
  • 1
    I regard if !unconfirmedDataFromSocket.isEmpty { unconfirmedDataFromSocket[0].markAsResend() } not as ugly. Commented Aug 20, 2021 at 8:11
  • @RajaKishan I get this error: Cannot use mutating member on immutable value: 'first' is a get-only property Commented Aug 20, 2021 at 8:18

1 Answer 1

2

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.