Swift Basics
Constants
let height = 1.75
// Can't change later.Variables
var health = 10
// Start with lower letters
// You can assign many variables in one line
var height = 10, breadth = 15, width = 20Constants and Variables can use any character, even chinese or an emoji.
Annotations (don’t have to)
var health: Integer
var health, mana: Integer
// Annotating the TYPE
/* Types are:
- String
- Int
- Double
- Bool
- [other types] //Array
*/
// Need to indicate during function making.
// Don't need to indicate during normal usage. Because the system will infer what data type it is by what you inserted.Printing
var health = 10
print("Your health is \(health)")
// Swift's version of an f-stringRanges
a...b = a to b, inclusive
a..<b = a to b, exclusive
a... = a onwards
...b = until b
Logical operators
!a (not)
a && b (and)
a || b (or)
State properties
@State var playerCard = "card2"
// You need to add a @State to indicate properties that are SPECIAL because they affect the user interface.Conditional statements
if a > b {
// code
}
else if {
// code
}Arrays
var list = ["a", "b", "c"]
var list:[String] = ["a", "b", "c"]
list[0] = "n"
print(list)
>> ["n", "b", "c"]
// If using a structure
var menuItems:[MenuItem] = [firstItem, secondItem, thirdItem]Random
random(in: 2...14)Comments
// Comment
/* Comment over
two lines */Semicolons
var health = 10 ; let name = "Elkan"
// Semicolons lets you combine 2 lines of codeFloating point numbers
- Double: 64-bit FPN (min. 15dp) — used by default
- Float: 32-bit FPN (min. 6dp)
Exponent
var exponent = 1.25e2
>> 1.25 x 10^2See next
- Swift-Functions — declaring functions, return types, labels
- Swift-Structures — building custom data types