0
var arr = [4, 5, 23, 4, 5, 2, 3]
arr.filter({
    return true
})

I get the error 'Int' is not a subtype of (). What am I doing wrong? Everything I've read seems to indicate this should work.

2 Answers 2

2
var arr = [4, 5, 23, 4, 5, 2, 3]
let arr2 = arr.filter {
    _ in
    return true
}

Problems with your original code:

  • filter returns an array. If you don't capture it, nothing useful happens. Notice that I've captured it in another variable; you could also reassign to the original variable.

  • If a parameter is passed into an anonymous function, you must capture it. You can capture it namelessly, as here, or with a name, or as $0, but you cannot completely ignore it; you must acknowledge it. That is what my _ in does.

Sign up to request clarification or add additional context in comments.

6 Comments

What does the "i in" achieve?
@DougSmith Cool your jets, I haven't finished writing. Okay, now I have.
@DougSmith I've just posted a Swift tutorial; here's the section on anonymous functions: apeth.com/swiftBook/ch02.html#_anonymous_functions See especially the paragraph that starts "But note that if the anonymous function takes parameters, you must use them somehow."
Why would you submit it if you hadn't finished writing? Appreciate the link and the insight though, this helped a lot.
It was right. It just wasn't as perfect as I ultimately wanted it. :) I guess it would be for the same reason that you submitted your comment and then went back and edited it... eh?
|
0

You have to provide an index to the filter:

arr.filter({
    n in true
})

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.