Skip to content

Instantly share code, notes, and snippets.

@mlvea
Last active August 29, 2015 14:17
Show Gist options
  • Save mlvea/25cd96da813304ce27a9 to your computer and use it in GitHub Desktop.
Save mlvea/25cd96da813304ce27a9 to your computer and use it in GitHub Desktop.
Swift Funtions
//Swift Function
func keepCalmAndLearnSwift(){
println("Ohh yeah. Learning Swift")
}
//Swift function with parameters
func keepCalmAndLearn(language: String){
println("Ohh yeah. Learing \(language)")
}
//Parameter can have default value
func keepCalmAndLearn(language: String = "Swift"){
println("Ohh yeah, Learning \(language)")
}
//Swift function return.
//Time to say thanks to swift and remember to pass your name
func thanksSwift(from: String) -> String{
return "You are welcome " + from
}
//Know what! Swift function can return more than one value
//Swfit documentation has a very good example
func findMinMax(array: [Int]) -> (min: Int, max: Int){
var currentMin = array[0]
var currentMax = array[0]
for value in array{
//Warning there is redundent step here. Which is ignored for simplicity.
//ie. array[0] doesn't need to be checked.
//Solusion is array[1..<array.count]. What? Await on upcoming gist.
if value < currentMin{
currentMin = value
}
else if value > currentMax{
currentMax = value
}
}
return (currentMin,currentMax)
}
//Function Parameter Names
//All function parameters have a name
//These parameter names are only used within the body of the function
func containsCharacter(stringToSearch: String,characterToFind: Character) -> Bool{
for character in stringToSearch{
if character == characterToFind{
return true
}
}
return false
}
//We call this function
containsCharacter("Swift","S")
//Look, paramter names doesn't visible to caller
//What if we want to call function with named parameters.
//We have to define external parameter names
func containsCharacter(stringToSearch string: String,characterToFind characterToFind: Character) -> Bool{
for character in stringToSearch{
if character == characterToFind{
return true
}
}
return false
}
// Now what? we can call it with named params.
containsCharacter(stringToSearch:"Swift",characterToFind:"S")
//However there is a short hand if both external parameters and internal parameters are same
//Use # before the name and only once
//Cool
func containsCharacter(#string: String, #characterToFind: Character) -> Bool{
for character in string{
if character == characterToFind{
return true
}
}
return false
}
//We call this one
containsCharacter(string:"Swift",characterToFind:"S")
//Variadic Parameters
//Variadic parameters accept zero or more values of a specified type
//Can be used to pass varing number of params to function
//In cricket as usual averge is sum of scores divided by number of dismissals
func averageOfPlayer(dismissals: Int,scores: Double...) -> Double{
//numbers parameter available as a constant array called numbers of type [Double]
var total: Double = 0
for score in scores{
total += score
}
return total/Double(dismissals)
}
//Lets calculate SL's Kumar Sangakkara's average upto Super 8 (Cricket World Cup 2015)
//4 is number of dismissals and rest of the elements will serve as scores
averageOfPlayer(4,39,7,105,117,104,124) // Output 124.0
//This is the call template averageOfPlayer(<#dismissals: Int#>, <#scores: Double#>...)
//Swift function parameters are constant by default
//Try and find out
func testParameter(number: Int){
//If you try
number = 5
//Error! - Cannot assign to let value 'number'
//OK Confiremed function parameters are constant
}
//But we can make it variable. We need to tell the compiler
func testParameter(var number: Int){
number = 5
//All is well.
//This will give a modifiable copy of parameter's value to function to work with
}
//However it is local copy of parameter value. Changes will vanish after the function scope
//What if we want otherwise. Next Gist. 'inout_function_params.swift'
//Inout function parameters
//We can mark functin paramters as input to pass variables to function by reference
func swapTwoInts(inout a: Int,input b: Int){
let temporyA = a
a = b
b = temporyA
}
//This function can only be called with variables. No constants no literals. because they cannot be modified
//ie
swapTwoInts(2,3) // Error -> Type input Int doesn not confirm to IntegerLiteralConvertible protocol.
// The what???
// I explained LiteralConvertible protocol here
// http://stackoverflow.com/a/28935922/1239426
//The variable names have to be prefixed by ampersand when calling the method
var firstInt = 3
var secontInd = 107
swapTwoInts(&firstInt, &secondInt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment