This page has moved to swiftly.dev/cheatsheet! The archive below will not be updated.
Visit Swiftly for more Swift guides.
let myInt = 5
let myString = "5.5"
var myInt = 5
myInt = myInt + 5
let myInt: Int = 5
let myString: String = "5.5"
if 5 > 3 {
print("5 is more than 3")
} else {
print("5 is not more than 3")
}
// Output: "5 is more than 3"
let myInt: Int? = 5
if let unwrappedInt = myInt {
print("myInt is \(unwrappedInt)")
}
// Output: "myInt is 5"
enum CompassPoint {
case north, south, east, west
}
var direction: CompassPoint = .north
switch direction {
case .north: print("Going north!")
case .south: print("Going south...")
default: print("Going east or west.")
}
// Output: "Going north!"
func square(x: Int) -> Int {
let squaredValue = x * x
return squaredValue
}
let squareOf6 = square(x: 6)
print("Square of 6 is: \(squareOf6)")
// Output: "Square of 6 is: 36"
struct MyStruct {
var myInt: Int
let myStr: String
mutating func squareMyInt() {
myInt = myInt * myInt
}
}
var obj = MyStruct(myInt: 5,
myStr: "Hi! 👋")
obj.squareMyInt()
print("\(obj.myStr) \(obj.myInt)")
// Output: "Hi! 👋 25"
var myArr = [1, 3]
myArr.append(5)
var sum = 0
for element in myArr {
sum += element
}
print(sum)
// Output: "9"