Reputation: 13103
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:
&
first
variableBut I was hoping for something more nicer.
Upvotes: 0
Views: 155
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