This content will (eventually) be mirrored on my site: http://www.h4labs.com/dev/ios/swift_cookbook.html
This repo will be mainly about the Swift language. I have another repo with small iOS projects
Swift 5.x compatible
- Basics | Colors | Date and Time | Sorting | Strings | Functional Swift
- Collections: Arrays | Dictionaries | Sets |
Common types: Int, String, Bool, CGFloat, Double, Float
let is used to declare immutable values, while var is used to declare mutable variables.
letlanguage="Swift" // Immutable String
vari=0 // mutable Int
i +=1varx:CGFloat=2varname:Stringletmax:Int
max =99varisDone=false // Boolletfuel=9letmsg:String // Must assign in all cases
if fuel <10{
msg ="Fuel dangerously low: \(fuel)"}elseif fuel <50{
msg ="Fuel low: \(fuel)"}else{
msg ="Fuel OK"}letcolor=Bool.random()?"red":"black"switch ticker {case"AAPL":
case "GOOGL":
case "MSFT":default:}foriin0..<10{print("\(i)")}foriin0...9{print("\(i)")}forcompanyin["Apple","Google","Microsoft"]{print("\(company)")}func add1(i:Int)->Int{ i +1} // return word not needed if we have 1 expression
letr0=add1(i:1) // 2Same function but add _ to not need a named parameter
func add1(_ i:Int)->Int{ i +1} // return word not needed if we have 1 expression
letr0=add1(1) // 2func bestLanguage()->(String,Int){return("Swift",1)}let(language, rank)=bestLanguage()letrnd=Int.random(in:0...1) // 0 or 1
Bool.random() // true or false
Int.random(in:20...29) // Random in range 20 through 29
Float.random(in:0...1) // Random between 0 and 1
[1,2,3].randomElement() // random Array element
Set([1,2,3]).randomElement() // random Set elementSometimes, it's better to shuffle an Array then simply iterate of the result to get a random element. This allows each element to be chosen at random exactly once.
letshuffled=[1,2,3].shuffled()