Skip to content

Instantly share code, notes, and snippets.

@pythonicrubyist
Last active August 29, 2015 14:15
Show Gist options
  • Save pythonicrubyist/1ed787d4753779b62aa7 to your computer and use it in GitHub Desktop.
Save pythonicrubyist/1ed787d4753779b62aa7 to your computer and use it in GitHub Desktop.
Control Flow in Swift
// Playground - noun: a place where people can play
import UIKit
// 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment