Swift and Python side by side
How does Swift compare to Python compare in terms of programming experience?
Created:
Introduction
Lets print “Hello, world!”
$ pythonprint("Hello, world!")
$ swift1> print("Hello, world!")
, world! Hello
Exactly same code!. What happens if I use single-quoted string?
$ pythonprint('Hello, world!')
$ swift1> print('Hello, world!')
: repl.swift:1:7: error: single-quoted string literal found, use '"'
error('Hello, World!')
print^~~~~~~~~~~~
"Hello, World!"
Notes:
- Single quotes do not work in Swift
- The error messages in Swift are helpful! It even suggests the correct quoting in this case.
Strings
How about string formatting?
print('%s had %d %s' % ('mary', 10, 'apples'))
(String(format: "%@ had %d %@", "mary", 10, "apples"))
print
10 apples mary had
The %@
is weird; which is defined here
But, Swift’s native string formatting is more on the lines of
= 'Mary'
name = 10
count = 'Apples'
fruit print('%(name)s had %(count)d %(fruit)s' % locals())
10 Apples Mary had
Swift uses \(variable)
for string interpolation.
let name = "Mary"
let count = 10
let fruit = "Apples"
("\(name) had \(count) \(fruit)") print
Control flow
Enough Strings, lets do loops:
for i in range(2):
print("Hello!")
!
Hello! Hello
The curly-braces are a’coming! Brace for it.
for i in 0..<2 {
("Hello!")
print}
!
Hello! Hello
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.