Learn to Make Web Apps with Real-World Swift Projects Paul Hudson Contents
Total Page:16
File Type:pdf, Size:1020Kb
HACKING WITH SWIFT 4&37&34*%& 48*'5 COMPLETE TUTORIAL COURSE Learn to make web apps with real-world Swift projects Paul Hudson Contents Preface 6 About this book Why does Kitura exist? A note for existing Swift developers Configuring your machine Introduction: Swift for Complete Beginners 21 How to install Xcode and create a playground Variables and constants Types of Data Operators String interpolation Arrays Dictionaries Conditional statements Loops Switch case Functions Optionals Optional chaining Enumerations Structs Classes Properties Static properties and methods Access control Polymorphism and typecasting Closures Wrap up Million Hairs 101 Setting up Swift packages explained Starting a server Routing user requests Writing HTML Matching custom routes Making it look good www.hackingwithswift.com 2 Wrap up CouchDB Poll 139 Setting up CouchDB from scratch Designing a JSON API Bringing CouchDB and Kitura together Creating CouchDB documents Casting a vote Wrap up Routing 178 Setting up Chaining routes Reading user data Routing regular expressions Wrap up Swift Fan Club 191 Setting up Listing forums Querying with a key Closures within closures Users and sessions Posting messages and replies Wrap up Meme Machine 237 Setting up Reading files from disk Multi-part form encoding Wrap up Templates 251 Setting up Recap on the basics Filters and tags Wrap up Barkr 265 Setting up www.hackingwithswift.com 3 An SQL primer Integrating MySQL with Kitura Generating tokens Reading insert IDs Over to you: fuzzy search Wrap up ASCII art 300 Setting up Updating pages interactively Reading remote images Wrap up Databases 316 Setting up Indexing for performance Normalization for efficiency Referential integrity for organization Transactions for consistency Default values for safety Wrap up Instant Coder 333 Setting up Say hello with GitHub Rendering the basic UI Creating new accounts Routing to success Creating new projects Finding places to work Wrap up AppleFanatic 370 Setting up Bootstrapping our servers Fetching stories from a database IDs, slugs, and Markdown Stories and errors Browsing by category Creating an admin section Wrap up www.hackingwithswift.com 4 Testing 422 Setting up Bootstrapping XCTest Testing our routes Wrap up www.hackingwithswift.com 5 Preface www.hackingwithswift.com 6 About this book The Server-Side Swift tutorial series is designed to make it easy for beginners to get started building web apps and websites using the Swift programming language. My teaching method skips out a lot of theory. It skips out the smart techniques that transform 20 lines of easy-to-understand code into 1 line of near-magic. It ignores coding conventions by the dozen. And perhaps later on, once you've finished, you'll want to go back and learn all the theory I so blithely walked past. But let me tell you this: the problem with learning theory by itself is that your brain doesn't really have any interest in remembering stuff just for the sake of it. You see, here you'll be learning to code on a Need To Know basis. Nearly everything you learn from me will have a direct, practical application to something we're working on. That way, your brain can see exactly why a certain technique is helpful and you can start using it straight away. This book has been written on the back of my personal motto: "Programming is an art. Don't spend all your time sharpening your pencil when you should be drawing." We'll be doing some "sharpening" but a heck of a lot more "drawing" – if that doesn't suit your way of learning, you should exit now. The three golden rules The series is crafted around a few basic tenets, and it's important you understand them before continuing: 1. Follow the series: The tutorials are designed to be used in order, starting at the beginning and working through to the end. The reason for this is that concepts are introduced sequentially on a need-to-know basis – you only learn about something when you really have to in order to make the project work. 2. Don't skip the technique projects: The tutorials follow a sequence that places a technique project after every two app projects. That is, you develop two apps then we focus on a particular component to help make your code better. The apps are standalone projects that you can go on to develop as you wish, whereas the technique tutorials will often be used to improve or prepare you for other projects. www.hackingwithswift.com 7 3. Get ready to hack: This is not designed to be the one-stop learning solution for all your Swift needs. The goal of each project is to reach the end with as little complication as possible, while learning one or more things along the way. I can't re-iterate that last point enough. What I have found time and time again is that any tutorial, no matter how carefully written or what audience it's aimed at, will fail to fit the needs of many possible readers. And these people get angry, saying how the tutorial is wrong, how the tutorial is lame, how their tutorial would be much better if only they had the time to write it, and so on. Over the last 12 years of writing, I have learned to ignore minority whinging and move on, because what matters is that this tutorial is useful to you. You'd be surprised by how many people think the path to success is through reading books, attending classes or, well, doing pretty much anything except sitting down in front of a computer and typing. Not me. I believe the best way to learn something is to try to do it yourself and see how it goes. Sure, going to classes might re-enforce what you've learned, or it might teach you some time- saving techniques, but ultimately I've met too many people with computing degrees who stumble when asked to write simple programs. Don't believe me? Try doing a Google search for "fizz buzz test", and you'll be surprised too. So, dive in, make things, and please, please, please have fun – because if you're not enjoying yourself, Swift coding probably isn't for you. If you spot any errors in this book, either typos or technical mistakes, please do let me know so I can correct them as soon as possible. The best way to get in touch is on Twitter @twostraws, but you can also email [email protected]. Xcode, Swift and Kitura I'm not going to talk much, because I want to get straight into coding. However, there are some points you do need to know: www.hackingwithswift.com 8 • I’ve written these tutorials using Xcode 8.1, which is available for free from the Mac App Store. If you’re using an earlier version of Xcode you should upgrade before continuing otherwise you may encounter bugs. • If you’re using Linux or considering using Linux, please read the introductory chapter “A note on Linux”. • Swift is a relatively new language, and is evolving quickly. Every new release of Xcode seems to change something or other, and often that means code that used to work now no longer does. At the time of writing, Swift is mature enough that the changes are relatively minor, so hopefully you can make them yourself. If not, check to see if there's an update of the project files on hackingwithswift.com. • These projects are designed to work with Kitura 1.0 or later. Please upgrade your system otherwise you’ll find this book very confusing indeed! Important note: if any bugs are found in the project files, or if Swift updates come out that force syntax changes, I'm going to be updating this book as needed. You should follow me on Twitter @twostraws if you want to be notified of updates. I'm also happy to answer questions on Twitter if you encounter problems, so please feel free to get in touch! Swift, the Swift logo, Xcode, Instruments, Cocoa Touch, Touch ID, AirDrop, iBeacon, iMessage, iPhone, iPad, Safari, App Store, Mac, and macOS are trademarks of Apple Inc., registered in the U.S. and other countries. Server-Side Swift is copyright Paul Hudson. All rights reserved. No part of this book or corresponding materials (such as text, images, or source code) may be reproduced or distributed by any means without prior written permission of the copyright owner. Acknowledgements I'd like to thank Ankit Aggarwal for his invaluable help and advice with the Swift package manager. It's a fast-developing part of our ecosystem, but Ankit is doing a great job documenting all the changes and supporting everyone who has questions. I'm also grateful to Kyle Fuller for being so responsive with answers, features, and fixes to his www.hackingwithswift.com 9 Stencil template engine. His work made my life a great deal easier, and I look forward to seeing where Stencil goes next! Dedication This book is dedicated to IBM's Kitura team, who have patiently answered my many questions on their Slack channel. Chris Bailey, Shmuel Kallner, Youming Lin, Ian Partridge, and others – thank you! www.hackingwithswift.com 10 Why does Kitura exist? It doesn’t matter whether you’ve been using iOS, macOS, watchOS, or tvOS – they are all very different to working on the server. Taking iOS as an example, you’re already used to the idea that apps are built using multiple layers. Here are some of them: 1. The Swift programming language provides us with basic syntax and functionality like func, var, as well as closures, classes, and so on.