Constants and Variables
let pi = 3.14
var r = 1
while r < 100 {
let sqr = r * r * pi
print("Radius: \(r); Square: \(sqr)")
r += 1
}
let
decalres a constant
var
declares a variable
Always declare a constant unless absolutely necessary
Basic Datatypes
let i: Int = 1 // default Int is either Int32 or Int64
let f: Float = 2.7
let d: Double = 3.1
let b: Bool = true
let s: String = "hello"
Swift can infer type of a variable
let x = 5, y = 3.142, z = true
let names = ["Alex", "Anna", "Ivan", "Maria"]
Type Conversion
Swift is type-safe language
var pi = 3 + 0.14 // literals don't have explicit type
let three = 3
let pointOneFour = 0.14
pi = Double(three) + pointOneFour
// implicit type conversions are not allowed
let roundPi:Int = Int(pi)
All type conversions must be explicit
Functions
func greet(person: String, from hometown: String) -> String {
return "Hello, \(person)! Glad you could visit from \(hometown)!"
}
print(greet(person: "Ivan", from: "Rostov"))
Every parameter has a name and an argument label
Arguments must be labeled when function is called
Optionals
let someNum = "3.14"
let number = Double(someNum) // Double?
if number != nil {
print("parsed number: \(number!)") // unwraped value is 3.14
}
Optional value contains either value or nil
Always make sure optional contains a value before foced unwraping
Conditional Statement
let someChar: Character = "z"
if someChar >= "0" && someChar <= "9" {
print("This is a digit.")
} else if someChar >= "a" && someChar <= "z" {
print("This is a letter.")
}
Curved braces are required
Optional Binding
let someNum = "3.14"
if let number = Double(someNum) { // number is Double!
print("parsed number: \(number)")
} else {
print("\(someNum) is not a number") // number is not reachable
}
Bound optional always contains a value
Conditional Statement – Switch
let someChar: Character = "z"
switch (someChar) {
case "a":
print("It is the first letter of the alphabet")
case "b"..."y":
print("It is some other letter of the alphabet")
case "z":
print("It is the last letter of the alphabet")
default:
print("It is some other character")
}
Case must always have a body
Loops
var i = 0
while i < 5 {
i += 1
}
repeat {
i -= 1
} while i > 0
for i in 0...10 {
for j in 0... {
print(".")
}
print("\n")
}