Wednesday, 18 December 2019

Swift Short Notes : Swift Chapter 7 - Functions


swift function can be nested.
Syntax:
func function_Name ( argu1:DataType , argu2:DataType …) -> return_Type
{
}
For multiple written values use tuple.
Ex: func minMax(array: [Int]) -> (min: Int, max: Int)
{
return (currentMin, currentMax)
}
return type can be optional tuple means it can or can not have values.(with ? in end .i.e. (Int, Int)?).
local parameter name used when declaring/defining function (local name must be unique)and external parameter name is used when calling function (external name can not be unique). If want to omit external parameter name for second and subsequent then use _ instead of external name.

When calling function By default first parameter omits its external name and second subsequent parameters use their local name as external name.
func someFunction(externalParameterName localParameterName: Int)
{
// function body goes here, and can use localParameterName
}
if you provide an external parameter name for a parameter, that external name must always be used when you call the function.


Ex:
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))

Default parameter name like c++
func someFunction(parameterWithDefault: Int = 12) {}

Variadic Parameters ellipse ( … ). Zero or more value of specific type.
Ex:
func arithmeticMean(numbers: Double...) -> Double {
for number in numbers {
}}

In-Out Parameter:
Default function param are constant. Use inout when want to change value of param passed to function.Use & when passing variable.
In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.

Ex: func swapTwoInts(inout a: Int, inout _ b: Int) ;// place of inout changed in swift 4
func swapTwoInts(a: inout Int, _ b: inout Int)

function type (function pointer ) like in c .can be passed as argument to another function.
func addTwoInts(a: Int, _ b: Int) -> Int {}
var mathFunction: (Int, Int) -> Int = addTwoInts

Nested Functions: function inside function. Its not directly accessible. An enclosing function can also return one of its nested functions to allow the nested function to be used in another scope.

x

0 comments:

Post a Comment

Search This Blog

Powered by Blogger.

Blog Archive