0

I have a books array of struct Book that I am looping through trying to find if one of the book's properties is equal to a specific predefined value, and then I'd like to rearrange the element

if books.contains(where: { $0.structProperty == value }) {

    books.rearrange(from: $0, to: 1)
}

And this is the rearrange function declared in an array extension file

extension Array {
    mutating func rearrange(from: Int, to: Int) {
        insert(remove(at: from), at: to)
    }
}

With this setup I am getting this compile error:

Anonymous closure argument not contained in a closure

How can I go about achieving it without relying on a for loop?

1 Answer 1

1

contains(where:) returns a boolean indicating whether a matching element is present in the array or not, and

{
    books.rearrange(from: $0, to: 1)
}

is not a closure – it is a code block in the if-statement.

You need index(where:) which gives you the position of the first matching element (or nil if none is present):

if let idx = books.index(where: { $0.structProperty == value }) {
    books.rearrange(from: idx, to: 1)
}

Note also that the first index of an array is zero, so if your intention is to move the array element to the front then it should be

books.rearrange(from: idx, to: 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked. The reason I had it to: 1 is because I actually wanted to rearrange it to appear 2nd in a UITableView.

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.