// I need to

ModernizeUpgrade without breaking it RescueFix what someone else started Build NewTurn an idea into a product Reach More PeopleGet found, get used, include everyone

// Company

Case StudiesExpertiseAbout + CareersResourcesContact Book a call →
≡articleBuild New

Swift Journal: Day One

First impressions of Apple's Swift from a C, C++, and Objective-C developer: porting C code, nil handling, the Xcode playground, and a small iPhone app.

Art+Logic Sep 22, 20145 min read

From the Art+Logic archive · written in 2014. The tools may have moved on; the thinking still holds.

Photo of Checkpoint Charlie, Friedrichstraße, Berlin, Deutschland by Etienne Girardet on Unsplash

Learning a language is sometimes confusing

I decided to jump right into Swift without doing any research into the writing done over the past month so that my opinions were not colored. My background is in the C/C++ and, lately, Objective-C of which I’ve become quite fond. I approached Swift with the hope that it would provide the same kind of  power I’ve found Obj-C/Cocoa to have, but with some modern newness brought in from other successful languages. It is too early, and the tools are too fresh, for me to draw conclusions on how useful it will be for production code other than that it does look promising.

TL;DR after the jump wherein I detail experiences with the Xcode playground and a small Swift based iPhone app.

Smooth

Friction

The most obvious place to start in Xcode was the REPL environment, the Playground. This is what gave the Swift unveiling demo the wow factor with its blimps traveling on sinusoidal waves, and changes taking effect immediately. Yes, you can debug some code here, but don’t expect to do more than light computation.

The Swift Playground template comes with some Hello World code which doesn’t give many clues about syntax. I found  Apple’s Swift language guide and skimmed over the basics. I decided to start by porting some C code I had for calculating Pi through various methods. It was easy to translate into Swift. let defines is a constant, var is a mutable variable. func introduces a function definition. Types come after names in declarations. Functions use a cool -> to denote the return type after the familiar parameter declarations.

The rest is mostly C like, and mostly behaves as expected. Chris Lattner, the language designer, put the safety on that gun pointing at your foot: switch case statements don’t fall through by default, and arithmetic operators fail on overflow by default. Not to mention the very sane nil behavior mentioned above.

// Gregory-Leibniz approximation of π
// See https://gist.github.com/jbagley/9558879 for C implementation
var factor = -1.0
var piAccumulation = 4.0
var denom = 3.0
// If using in a playground beware this many iterations, try 2500 instead.
for i in 1…500000
{
  piAccumulation += factor * (4.0 / denom)
  denom += 2.0;
  factor *= -1.0;
}
println(piAccumulation)

Once I had my code correct, the REPL did its thing and immediately ran without my prompting. I expected it to complete in a couple seconds at most. Unfortunately the playground couldn’t really handle the two billion iterations this code needs to get 10 correct digits of π. It could barely do 5,000 iterations, slowing down to a crawl after about 2,500. Anything more than that had my recent model Mac Mini with 16 GB RAM gasping for breath, and Xcode was unresponsive.

The reason I knew exactly when the playground was crippled was exactly the cause of the performance degradation. To the right of almost every statement is some trace output such as the number of times a statement was executed. You can even get a graph of a variable’s values over time. Everything is tracked and after all that information piles up, playtime grinds to a halt. Great for debugging, not great for a quick and dirty computation session.

I tried a different version using only constants and tail recursion. Fewer things to track should result in more performance. It could do 5,000 iterations before it hit its crawling point and took around 15 seconds to do 10,000 iterations.

// Recursive implementation
func LeibnizPiApproximationFunc(#afterIterations: Int) -> Double
{
   // See http://stackoverflow.com/questions/24270693/nested-recursive-function-in-swift
   var ApproxPi: (Double, Double, Double, Int) -> Double = { _ in return 0.0 }
   ApproxPi =
   {
      (denom : Double, factor : Double, piAccum: Double, iteration: Int) -> Double in
      if (iteration == 0)
      {
         return piAccum
      }
      return ApproxPi(denom + 2.0,
         factor * -1.0,
         piAccum + (factor * (4.0 / denom)),
         iteration - 1)
   }
   return ApproxPi(3.0, -1.0, 4.0, afterIterations)
}
let i = 6000
println(LeibnizPiApproximationFunc(afterIterations: i))

To confirm that performance is a Playground-only problem I created an iOS app to perform the approximation and allow editing of the number of iterations. Here 500,000 iterations was noticeable, but less than a second. More interesting was how familiar it felt to write up a view controller. I didn’t try 2 billion, but 2 million completed within a second or two on an iPad 4.

Reddit as usual has some interesting things going on to help you try it out yourself. I think I will go there now.

Cocoaphony also has interesting posts on Swift.

keep going

More to explore in Build New.

All Build New resources →
let's talk

Got a problem like this one?

Tell us what's stuck. A real person replies within one business day.

Talk to our team →

Talk to people who know software, not a sales script.

Your first call is with Aja, our VP of Sales. He'll help make sure you're solving the right problem. Here's what you'll cover together:

  1. What you're trying to accomplish

    The business goal first, then the technology.

  2. Possible approaches

    And the tradeoffs of each, in plain language.

  3. Risks you may not have considered

    Technical and business, before they cost you.

  4. Whether AI changes the math

    What's practical, and what's just hype for your project.

  5. Sensible next steps

    Even if the right next step is not us.

book-a-call.ics

Loading the scheduler…

Open the booking page →

Some problems are easier to explain in writing. Send us a few lines about what you're working on, and we'll reply within one business day. Helpful to include:

  1. What the software does, or should do
  2. What's stuck, or what's worrying you
  3. Any deadline or budget you have in mind
note.md

Loading the form…