Book Image

Swift 2 By Example

By : Giordano Scalzo
Book Image

Swift 2 By Example

By: Giordano Scalzo

Overview of this book

Swift is no longer the unripe language it was when launched by Apple at WWDC14, now it’s a powerful and ready-for-production programming language that has empowered most new released apps. Swift is a user-friendly language with a smooth learning curve; it is safe, robust, and really flexible. Swift 2 is more powerful than ever; it introduces new ways to solve old problems, more robust error handling, and a new programming paradigm that favours composition over inheritance. Swift 2 by Example is a fast-paced, practical guide to help you learn how to develop iOS apps using Swift. Through the development of seven different iOS apps and one server app, you’ll find out how to use either the right feature of the language or the right tool to solve a given problem. We begin by introducing you to the latest features of Swift 2, further kick-starting your app development journey by building a guessing game app, followed by a memory game. It doesn’t end there, with a few more apps in store for you: a to-do list, a beautiful weather app, two games: Flappy Swift and Cube Runner, and finally an ecommerce app to top everything off. By the end of the book, you’ll be able to build well-designed apps, effectively use AutoLayout, develop videogames, and build server apps.
Table of Contents (18 chapters)
Swift 2 By Example
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Free Chapter
1
Welcome to the World of Swift
2
Building a Guess the Number App
Index

The ASAPServer


With the entire environment set, we can finally implement the ASAP Server.

The Products

In a real server, the products are probably saved in a database, but in our simple implementation, we will save the products in a file—the same file we used in the app.

So, let's start the implementation by saving the products.json file at the same level of makefile.

A DBRepository class will abstract the connection with the storage, making it easy to switch to a database, as we did in the app:

import Foundation

let dbRepository = DBRepository()

class DBRepository {
    func allProducts() -> String {
        print("Get /products")

        do {
            let productsAsNSString = try NSString(contentsOfFile: "products.json", 
                encoding: NSUTF8StringEncoding)
#if os(Linux)
            return productsAsNSString.bridge()
#else
            return productsAsNSString as String
#endif
        }
        catch {
            print("Error")
        }
        return "{ products: []...