5. Variables & Constants
Use `let` for constants and `var` for variables in Swift.
var str1 = "Hello" // Variable
str1 = "Test"
let str2 = "World" // Constant
str2 = "Test" // Compile error
var arr1: [Int] = [] // Mutable array
arr1.append(1)
let arr2: [Int] = [] // Immutable array
arr2.append(1) // Compile error
6. Printing
Use `println()` method. It s very similar to `NSLog()`.
Values of variables are expandable inside String using `()` like below.
let hello = "Hello"
let world = "世界"
println("(hello), (world)") // Hello, 世界
7. Optional
To indicate it might be `nil`.
Use `Optional<T>` to declare a variable, method as optional.
var str3: Optional<String> = nil
var str4: String? = nil // Syntax Sugar
8. Optional
`Optional<T>` is kind of `enum`.
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
/// Construct a `nil` instance.
init()
/// Construct a non- `nil` instance that stores `some`.
init(_ some: T)
So, it is able to express them.
var str5: Optional<String> = Optional<String>() // nil
var str6: Optional<String> = Optional<String>("Hello") // {Some "Hello"}
9. Optional
Use `!` mark after an optional value to force the unwrapping of its value.
var str6: Optional<String> = Optional<String>("Hello")
var str7: String = str6 // Compile error
var str8: String = str6! // "Hello"
An optional value fails when the optional is `nil`
var str5: Optional<String> = Optional<String>()
var str9: String = str5! // Runtime error
10. Switch
The `Switch` statement is like other languages.
Different points in Swift
Not only Integers.
Coverage case, all possible values.
`break` statement is NOT required.
Use `fallthrough` to go through explicitly
Adding other conditional statement
11. Switch
let country: String = "Canada"
switch country {
case "USA":
println("USA")
case "Canada":
println("Canada")
case "Japan":
fallthrough
default:
println("Other")
}
13. Tuple with Switch
var p: (x: Float, y: Float) = (1.0, 2.0)
println("x: (p.0), y: (p.1)")
println("x: (p.x), y: (p.y)")
switch p {
case (0, 0):
println("Point is on origin.")
case (_, 0):
println("Point is on X-axes.")
case (0, _):
println("Point is on Y-axes.")
case (-2...2, -2...2):
println("Point is inside the box")
default:
println("Point is outside the box")
}
14. Function
Use `func` keyword to declare.
func myPow(x: Int, e: Int) -> Int {
var d = 1
for _ in 1...e {
d *= x
}
return d
}
myPow(3, 4)
```
func [Name](arg1: Type1,..) -> [Return Type] {
// Procedure
}
```