|
Day 9 Closures, Paul Hudson talks about how useful Closures are to pass into the sorted(by: ) function, as in the example to put "Suzanne" in front of the other members of the array. It's made clear that the Closure you can pass into sorted(by: ) MUST be of the type that accepts two strings and returns one Bool. And that forms the basis for knowing how to read shorthand notation for Closures in the Day 9 examples. But, are you just supposed to know that the sorted(by: ) function can only accept this particular type of Closure? ie iOS developers know that sorted(by: ) will not take any other configuration of data type inputs/outputs. Because if you didn't know this, then it would also be a lot harder to make sense of the shorthand notation as well. It seems that this is pointed out in the documentation as shown here but it's a bit confusing becuse of the throws and rethrows https://developer.apple.com/documentation/swift/array/sorted(by:) (NB: There have been some previous threads on Closures and Sorted but they didn't quite answer what I was looking for) |
|
Xcode will usually provide enough hints that you can figure out what you need to pass into a closure. Also, yes, the documentation can provide explicit information. In the case of sorted(by:), you can tell what type of parameters you need to give it because that method is called on an You can see this in the method signature in the docs:
Don't worry so much about |
|
I see, that's very helpful. So the Closure itself returns a Bool. But then I can't just put in a simple Bool such as True or False as a parameter into sorted(by: ). I tried it and it doesn't work. So basically sorted(by: ) was designed specifically to be able to accept a Closure that takes two Strings or two Ints, etc and returns a Bool. Is that right? |
|
Right, because the parameter to The way
So you can see that just providing a
Yep. |
|
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.