Coming into this project you might thought strings were trivial, but I hope I’ve shown you that there’s more to them than meets the eye.
We’ve looked at how strings are different from arrays, how we can write useful extensions for strings, how Swift lets us combine functions together beautifully, and how
NSAttributedString lets us add formatting to strings.
Of course, we’ve only just scratched the surface of strings here, but the challenges below will encourage you to write some extensions of your own so you get a better feel for how it works.
Anyone can sit through a tutorial, but it takes actual work to remember what was taught. It’s my job to make sure you take as much from these tutorials as possible, so I’ve prepared a short review to help you check your learning.
One of the best ways to learn is to write your own code as often as possible, so here are three ways you should try your new knowledge to make sure you fully understand what’s going on:
Stringextension that adds a
withPrefix()method. If the string already contains the prefix it should return itself; if it doesn’t contain the prefix, it should return itself with the prefix added. For example:
"pet".withPrefix("car")should return “carpet”.
Stringextension that adds an
isNumericproperty that returns true if the string holds any sort of number. Tip: creating a
Stringis a failable initializer.
Stringextension that adds a
linesproperty that returns an array of all the lines in a string. So, “this\nis\na\ntest” should return an array with four elements.
SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
One of the most effective motivators of success is sharing your progress with other people – when you tell folks what you're doing and what you've learned, it encourages you to come back for more, which in turn will help you reach your app development goals faster.
So, now that you've done all the hard work it's time to share your success: tell folks that you've completed this project, either by clicking the button below to start composing a tweet, or by writing your own message from scratch. This will definitely encourage you to keep learning, but it will also help other folks discover my work – thank you!
Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and a speaker at Swift events around the world. If you're curious you can learn more here.
Link copied to your pasteboard.