swift-for-python-programmers

Basics

🏡

1. Variables and Constants

Unlike python, there are Variables and Constants in Swift

Constants, once defined using the let keyword cannot have their values changed

let count = 2;

You define Variables using var much like JavaScript

var step = 1;

1.1 Multiple declarations

var x = 1, y = 2, z = 3;

Whitespaces before and after the = are important!

2. Type Annotations

Annotations follow the same syntax as Python

var name: String
name = "As3tic" 

You can also annotate multiple related variables

var a,b,c: Double;

3. Printing & String Interpolation

print("Hello World")

var age = 2;

print(age)

Printing variables

let name = "As3tic"

print("My name is \(name)")

4. Comments

// single line comment

/* multi-line 
comment
*/

5. String formatting

String formatting is somewhat more convoluted in Swift

let person : String
person = "As3tic"

On one hand we have the string concetenation we’re all too familiar with

let greeting = "Hello, " + person

On the other we could do this

let greeting = String(format: "%@%x", "timeNow in hex: ", person)