Skip to content

Instantly share code, notes, and snippets.

@pythonicrubyist
Last active August 29, 2015 14:16
Show Gist options
  • Save pythonicrubyist/a50775fdf834b99357c6 to your computer and use it in GitHub Desktop.
Save pythonicrubyist/a50775fdf834b99357c6 to your computer and use it in GitHub Desktop.
Swift Fundamentals
// Variables in Swift
// Every variable in Swift is declared with the keyword "var".
// Swift is a type-safe language. It is strongly typed.
// All varables is Swift are of a specific type.
// Swift performs type inference if the type is not declared.
var s = "Hello World!" // Type inferred as string
var i = 7 // Type inferred as integer
var b = false // Type inferred as boolean
// b = "Hi" will throw a type error
// Type annotation means specifying the type without initializing the variable.
// : means "is of type"
var a : Int
var c : Character
var o : Bool
// You can specify both the default value and specify type.
var str : String = "Hi"
// COnstants in Swift
// Constants defined by the keyword "let" have to stay the same during the lifetime of the program.
// Use of constants are strongly recommended in Swift
// As a safty measure.
let r = 2
// String interpolation
var name = "Ramtin"
println("My name is \(name)")
// String Concatenation
var s1 = "a"
var s2 = "b"
println(s1 + ", " + s2)
// Type Casting
var i1 = 2
var d1 = 3.0
println(Double(i1) * d1)
// Flow management in Swift
// Parentheses are optional, curly braces are mandatory.
// condition must evaluate as a boolean.
var a = 5
var b = 10
if a < b {
println("a is less than b.")
} else if a > b {
println("a is bigger than b.")
} else {
println("a is equal to b")
}
// Switch statements are recommended.
switch a {
case 1...10:
println("\(a) is between 1 and 10")
default:
println("\(a) is not between 1 and 10")
}
var c: Character = "w"
switch c {
case ".", "!", "@", "#", "$":
println("\(c) is a special character.")
case "a", "e", "i", "o", "u":
println("\(c) is a vowel.")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
println("\(c) is a consonan.t")
default:
println("\(c) is neither a vowel, nor a consonant")
}
// Loops
// Closed inclusive range. Includes both sides.
for i in 1...100 {
println(i)
} // will print 1,2,3,,,,,100
// Half open range operator. Inludes the left side, not the right side.
for i in 1..<100 {
println(i)
} // will print 1,2,3,,,,,99
// Looping over characters of a string
for c in "Hellow World!" {
println(c)
}
var i = 0
while i < 10 {
println(i)
i = i+1
}
// do while executes at last once.
do {
println(i)
i = i+1
} while i < 10
// Functions
// Functions are self-contained chunks of code that perform a specific task.
func f1 () {
println("Hello World!")
}
f1()
func f2 (name : String){
println("Hello \(name)!")
}
f2("Ramtin")
func f3 (name : String, age : Int) {
println("Hello \(name)! Im \(age) yera(s) old.")
}
f3("Ramtin", 100)
func f4 (firstName : String, lastName : String) -> String {
return ("\(firstName) \(lastName)")
}
println(f4("Jogn", "Doe"))
// If a defalut avalue is specified in the parameters
// , the parameter should be named while calling the function
func f5 (name : String = "John Doe") -> String {
return ("Hello \(name)")
}
println(f5(name: "Ramtin"))
func f6 (a : Int = 4, b : Int = 5){
println("result is: \(a*b)")
}
f6() // 20
f6(a: 10) // 50
f6(b: 10) //40
f6(a:10, b:20) // 200
// Collections in Swift
// Two basic collection types in Swift, Arrays and Dictionaries.
// Arrays in Swift
// Ordered collections of items
// Zero based.
// Type safe
// If defined by let, it is immutable, can not be added or altered.
// If dfined by var, it is mutable, can be modifed and added.
var a1 = [2, 3, 4]
var a2 : [Int]
a1[2] = 8
a1.append(5)
a1 += [6]
a1.insert(1, atIndex: 0)
a1.removeLast() // removes the last item from array and returns the removed item.
a1.count
for i in a1 {
println(i)
}
// Dictionaries in Swift
// A dictionary is a collection of Key value pairs.
// keys are strrictly typed.
// Values are strictly typed.
var d1 = [1: "One", 2: "Two", 3: "Three"]
var d2 : [Int: String]
d1[4] = "Four"
d1[0] // returns nil
d1[1] //returns "ONe
d1.updateValue("FOUR", forKey: 4)
d1.removeValueForKey(4)
d1.count
for (k, v) in d1{
println("\(k) corresponds to \(v)")
}
// Tuples in Swift
// Tuples are a clollection of any items
var t1 = ("Ruby", 3, true)
// A function can return a tuple
func someFunction() -> (Int, String){
return (2, "Some string")
}
someFunction()
let r1 = someFunction()
r1.0 // returns 2
r1.1 // returns "Some String"
let (r2, r3) = someFunction()
r2 // returns 2
r3 // returns "Some String"
// Optionals in Swift
// Swift variables can not be null. That is just the rule.
// But under the two circomstances below, varaibles may be zeror
// 1) methods that cannot return a value.
// for example, "xyz".toInt()
// 2) properties that can not be initialized when an object is constructed.
var temperature :Int? // means that this variable can be an integer or nil
println("Temperature is: \(temperature)") // returns"Temperature is: nil"
temperature = 37
if temperature != nil{
println("Temperature is: \(temperature)") // returns "Temperature is: Optional(37)"
println("Temperature is: \(temperature!)") // returns ""Temperature is: 37""
}
// Enumerators in Swift
enum SteakPreference {
case wellDone
case medium
case rare
case blueRare
}
var mySteakPreference = SteakPreference.medium
var JackSteakPreference : SteakPreference
JackSteakPreference = .wellDone
// Closures in Swift
// A self-cntained, reusable group of code
// A function is a type of closure.
let c1 = {
println("Hello World!")
}
func f1 (c : ()->()){
for i in 1...5 {
c()
}
}
f1(c1)
func f2 ()->(){
println("Hello World!")
}
// Turning aboce function into a closure:
var c2 = {
()->() in
println("Hello World!")
}
f1({()->() in println("Hello World!")})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment