Swift and Python side by side

Published: 2017-03-31 by Pradeep Gowda.
Tagged: python, swift


Lets print “Hello, world!”

$ python
print("Hello, world!")
$ swift
1> print("Hello, world!")
Hello, world!

Exactly same code!. What happens if I use single-quoted string?

$ python
print('Hello, world!')
$ swift
1> print('Hello, world!')
error: repl.swift:1:7: error: single-quoted string literal found, use '"'
print('Hello, World!')
      "Hello, World!"


  1. Single quotes do not work in Swift
  2. The error messages in Swift are helpful! It even suggests the correct quoting in this case.


How about string formatting?

print('%s had %d %s' % ('mary', 10, 'apples'))
print(String(format: "%@ had %d %@", "mary", 10, "apples"))

mary had 10 apples

The %@ is weird; which is defined here

But, Swift’s native string formatting is more on the lines of

name = 'Mary'
count = 10
fruit = 'Apples'
print('%(name)s had %(count)d %(fruit)s' % locals())

Mary had 10 Apples

Swift uses \(variable) for string interpolation.

let name = "Mary"
let count = 10
let fruit = "Apples"
print("\(name) had \(count) \(fruit)")

Control flow

Enough Strings, lets do loops:

for i in range(2):


The curly-braces are a’coming! Brace for it.

for i in 0..<2 {


I actually think this range operator 0..<2 is very explicit about the number generated to be less than 2, which is a good thing.