|
Question I am trying to port the following Rust function to Swift. This is taken from the book Learning Rust 2nd Ed. from O'Reilly (the code is freely copyable for learning purposes so I don't feel bad about pasting it here). I just can't get a generic Swift function to work and was hoping to throw this out there for those who fancy a challenge. It's been bugging me that I can't find a solution so it's time to let the experts loose on it!
We would invoke it in a Rust program like this:
Now the rust compiler is very clever and even though this is the first declaration of "bounds" it can see that it's passed into another function later on as a
What we have here is a generic function which expects the type to implement the Aside: Rust does not require a Hopefully that all makes sense. Once you get used to it Rust's syntax is quite succinct and direct. Note that Right, that's the background. Let's switch over to Swift! The first thing that we need to do in Swift is see if there's a protocol which is equivalent to The other thing to note is that the Swift Another thing about the Rust function is that the Another difference with Swift is that it doesn't allow you to pass the type to a generic function invocation. So you can't do this:
The solution is to pass the type in to the function as a parameter. This simplifies the job of the compiler (I guess) and it's also a solution that Apple uses in several places. Anyway, putting it all together, this is the best I could come up with:
This compiles. However, if I try to invoke it like this:
I get a lovely error message:
At this point I'm going to mull it over and try again tomorrow. It can't possibly be this hard! What does everyone think? Add an Extension to String to give it a Decoder? Define a new protocol Or am I missing something already built in to Swift? Apologies for the length of this and for polluting the forums with non-Swift code! And thanks for making it this far. |
|
Update: I found a solution! The appropriate protocol is
🤦 |
SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!
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.