Introduction
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!"
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'))
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):
print("Hello!")
Hello!
Hello!
The curly-braces are a’coming! Brace for it.
for i in 0..<2 {
print("Hello!")
}
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.