Swift3 or node.Js?

I’m a full-stack developer, so I build my iOS applications in Swift and backends in Node.js… why not use Swift for both platforms (iOS and backend)?

swift-logo

Well, now is possible!

Swift official website: https://swift.org/about/#platform-support

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

The goal of the Swift project is to create the best available language for uses ranging from systems programming, to mobile and desktop apps, scaling up to cloud services. Most importantly, Swift is designed to make writing and maintaining correct programs easier for the developer.

With the becoming of Swift open source, we can use it as server-side language using a lot of different frameworks.

More specifically:

Perfect

perfect-logo-300x300

Perfect is a web server and toolkit for developers using the Swift programming language to build applications and other REST services. It lets developers build using only Swift to program both the client-facing and server-side of their projects. It’s the ideal backbone for cloud and mobile technologies. Developers can be more productive and efficient using Perfect to write less code and work in one fundamental language for all their needs.

Official web-site: http://perfect.org/

Hello World example

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import PerfectLib
public func PerfectServerModuleInit() {
Routing.Handler.registerGlobally()

Routing.Routes[“/”] = { _ in return HelloWorldHandler() }
}

class HelloWorldHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.appendBodyString(“Hello, World!”)
response.requestCompletedCallback()
}
}
}[/code]


Vapor

vapor-logo-1-300x135

Vapor is a Web Framework for Swift that works on iOS, macOS, and Ubuntu.
Vapor is the most used web framework for Swift. It provides a beautifully expressive and easy to use foundation for your next website or API.

Official web-site: https://vapor.codes/

Hello World example

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import Vapor
let app = Application()

app.get(“/”) { request in
return “Hello, World!”
}

app.start()[/code]


Kitura

KituraLogo-300x175

Kitura is a new, modular, package-based web framework written in the Swift language. Install, create and deploy in under 3 minutes.
Kitura scales out of the box, thanks to Grand Central Dispatch. Create your app using Foundation APIs you already know, on macOS and Linux. Manage dependencies and versioning with Swift Package Manager.

Official web-site: http://www.kitura.io/

Hello World example

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import Kitura
let router = Router()

router.get(“/”) { request, response, next in
response.send(“Hello, World!”)
next()
}

Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()[/code]


Zewo

zewo-logo-300x300

Zewo is a set of open source libraries that help you build
modern and blazing fast server software.
Thanks to Zewo’s modularity, you can pick and choose what you want to use for your own framework – whether it be Venice for concurrency, the HTTP Server, the included Trie-based router matcher for your Router, or one of our many other components.

Official web-site: http://www.zewo.io/

Hello World example

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import HTTPServer
import Router
let app = Router { route in
route.get(“/”) { _ in
return Response(body: “Hello, World!”)
}
}

try Server(app).start()[/code]


Benefits of Swift server side

  • Same code runs in both places
  • Reduce development time by sharing code
  • Leverage great APIs on the serve
  • High performance
  • Better memory and thread optimization

Screen-Shot-2016-06-15-at-1.29.01-PM

Why use Swift on backend?

Node.js, rose to popularity because it enables “full-stack” developers to work on both the frontend and backend of their web apps. This allows teams to iterate faster, ultimately leading to more successful products. Swift decreases the iteration time for mobile development teams in the same way.

Is the new trending language: http://stackoverflow.com/research/developer-survey-2016

top-trend-01
top-trend-02

Good, but where to deploy?

20161027174404!Heroku_logo

Personally i like Heroku (https://www.heroku.com/), is easy to use and fast to deploy.
Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

I tried Vapor as framework, and the deploy is “automatic” managed by itself, simply typing:

vapor heroku init

The Heroku CLI will ask four questions:
1) Would you like to provide a custom Heroku app name?
2) Would you like to provide a custom Heroku buildpack?
3) Are you using a custom Executable name?
4) Would you like to push to Heroku now?

json-swift

Well, very easy… will take ~10 minutes to deploy.

The JSON in the screenshot is a MongoDB connection that retrieve a list of data, made up using Swift and Xcode.

I’ve used a simple middleware on each http request and the MongoDB package (MongoKitten).

Snippet example code:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import Vapor
import Auth
import HTTP

let drop = Droplet()

// simple “/” route
drop.get(“/”) { request in
return try JSON(node: [“response”: “ok”])
}

// sample and raw mongo query
drop.get(“/demoget/: world”) {
request in
let db = mongoDB ? [“scores”]

guard
let world = request.parameters[“world”] ? .string
else {
throw Abort.badRequest
}

guard
let scores =
try db ? .find(matching: “world” == world)
else {
return try JSON(node: [“response”: “no data in db…”])
}

var retVal = [JSON]()
for item: Document in scores {
var itemWorld = item.dictionaryValue[“world”] ? .string ? ? “–”
var itemLevel = item.dictionaryValue[“level”] ? .string ? ? “–”
var itemScore = item.dictionaryValue[“score”] ? .string ? ? “–”

var jn =
try JSON(node: [“world”: itemWorld, “level”: itemLevel, “score”: itemScore])

retVal += jn
}

return try JSON(node: retVal)
}

drop.run()[/code]

Very draft, just to show the MongoDB query done in Swift.

xcode-swift-mongo-02
xcode-swift-mongo-01

Final notes

Personally I know Swift, and now I’m started to convert all of my backend small project (done in node.js) in Swift3 to Heroku.

There are a lot of package that you can use. MongoDBpostgreSQL, lot of middlewarenetworkJSON, etc…
This is an extract of Vapor packages: https://vapor.github.io/documentation/#packages

Hope that Swift reach a stable version in order to use it effective in a production environment.

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.