An Introduction to Swift from a Python Perspective

Ben Ackland

With a history of writing software using Python (primarily for web application development), I look at some of the basics of Apple’s new Swift programming language.

Swift

Back in 2014 Apple introduced a new programming language called Swift, marketing it as a “powerful and intuitive programming language for iOS, OS X, and watchOS”. The obvious strengths over Objective-C (which is around 20 years old) being improved code readability and a reduced learning curve. I recently spent two days with Richard from Amsys – an Apple Authorised Training Centre – learning some more about the second release of this new language, Swift 2, which will be formally released in autumn 2015.

My coding background is in Python, a language which historically is quite easy to get into, has very readable code, and is highly extendible. At Netsight we have a truckload of experience with Python, as well as experience with Objective-C (iPhone apps, OS X tools). After seeing Apple’s original keynote on Swift, I was keen to learn what it could mean for us as an Internet solutions company.

Having myself developed a few apps in Objective-C in the past I was pleasantly surprised to find that Swift was quite clearly an improvement for my use case, and a lot more fun to get your teeth into. It clearly borrows quite a few concepts from Python (and other languages such as Haskell) so no surprise that it didn’t take me long to get stuck in.

Here I try to provide a summary of some of the main differences I noted coming from a Python background, for the benefit of my colleagues and anyone else who is interested.

A quick disclaimer: I’m new to Swift so I’m sure there will be a host of alternate ways to achieve similar results. Feedback is very welcome!


Basic Syntax

Code blocks in Python are prefixed with a colon (:), example:

def say_hello_to(name=””):
      print “Hello %s” % name

Code blocks in Swift are surrounded by curly braces {}, similar to Java or C:

func say_hello_to(name:String) {
    print("Hello \(name)")
}

Constants and Variables

let x = “a variable whose value will never change”
var y = “a variable whose value can change”

Data Structures

  • Lists in Python are like Arrays in Swift [1,2,3]
  • Tuples are like Tuples (1,2,3)
  • Dictionaries are like Dictionaries {“a”:1, “b”:2, “c”:3}

Built-in Functions, Operators, String Formatting

Python 2.7 Swift 2 Notes
print x
print(x)
It may take a while to break the habit! Note that “print(x)” also works in Python 2.7.
and
&&
or
||
Two vertical bars.
range(1,6)
1...5
[1,2,3,4,5]
range(1,5)
1..<5
[1,2,3,4]
string.startswith()
String.hasPrefix()
string.endswith()
String.hasSuffix()
len(string)
String.characters.count
Not String.length or String.count
x in y
x.contains(y)
None
nil
Not exactly the same, but close.
len(array)
array.count
"The day of the week 
is %s" % day
"The day of the week 
is \(day)"
‘Look for the "lost 
children" sign’
"Look for the \"lost 
children\" sign"
You don’t appear to be able to use single quotes to denote strings.

Comments

// comment
/* long comment */
/// documentation
//* lots of documentation *//

Copying and Referencing

When you assign something to a constant or variable, you may want a complete copy of the original data or structure to be made, or you may want to refer to the original data or structure (without taking a copy). My basic understanding of this in Swift:

let a = something_that_is_not_a_class
let x = a takes a copy
let c = a_class
let x = c makes a reference

You can use the & operator to explicitly pass a reference to a variable into a function, as an “in-out” parameter:

func addTwo(inout i: Int) {
    i += 2
}
var one = 1
addTwo(&one)
print(one) // 3

(The above example was kindly contributed by oisdk.)

Character Indices and Ranges

Out-of-the-box, addressing sub-strings with integer ranges isn’t possible, something we take for granted in Python. String ranges have to be constructed from String.Index values, not from plain integers:

let startIndex = advance(digits.startIndex, 3)
let endIndex = advance(startIndex, 4)
let range = Range(start: startIndex, end: endIndex)
let someDigits = digits[range]      // -> "3456"

Yes, that’s a lot of code to do the equivalent of “digits[3:7]” in Python. But you can extend String to work with integer indices if you so wish, although it’s not advised (login to read why).


A few other useful tips:

Swift 2

  • x === y (triple equals) evaluates whether x and y are exactly the same object in memory
  • You can pad numbers with underscores for readability: 1_000_000 = 1000000
  • Markdown is possible in inline documentation

Xcode

  • The variable __LINE__ is the current line number (for debugging)
  • Use “Edit all in scope” context menu on a variable to rename that variable everywhere in the current scope

What also struck me while writing a few small sample applications is that Apple have done their homework – they’ve applied their approach to delivering good hardware and software to development – taking the best of breed and amalgamating it into a new technology that’s as usable as possible.

If you’re new to Swift and interested in developing iOS and OS X apps, I suggest reading Apple’s introduction as a first step: A Swift Tour. If you’re coming from a Python background, I hope the above is also useful in your first few days.

Happy coding!

SHARE THIS
Tweet about this on TwitterShare on FacebookShare on Google+