+ 1

I cant understand inout.

please help. Thanks in advance

3rd Sep 2016, 8:44 AM
Ruchi Gupta
Ruchi Gupta - avatar
3 odpowiedzi
+ 1
We use inout keyword when we have to compute arguments values for some raison and return them back, like swapTwoNumbers or getTheGreatestCommonFactor. Example: func gcfof(inout m: Int, inout n: Int) { // used inout key to be able to modify the arguments while n != 0 { let remainder = m % n m = n n = remainder } print(m) } // Example var a = 120 var b = 16 print("The greatest common factor of \(a) and \(b) is", terminator: " ") gcfof(&a, n: &b) // & before the argument to tell the compiler that I am changing this inputs /*Output The greatest common factor of 120 and 16 is 8*/ Happy coding
5th Sep 2016, 10:11 PM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
+ 1
var score = 0 // score to increment when a player collect a coin. //function that takes a number, increments it by 1 and returns the result func incrementScore(a: Int)->Int { a += 1 // compiler will complain cause the argument is a constant that you can't change. return a } score = incrementScore(score) // will throw an error. // we could avoid this by editing our increment function like this: func increment(a: Int)->Int { let b = a + 1 return b } score = incrementScore(score) // would work now // The new inout keyword !! // here it is func incrementScore(inout a: Int) ->Int { a += 1 return a } score = incrementScore(&score) // we add & before the argument score to tell the compiler that this input would be changed andlet the function do it Hope this helps.
6th Sep 2016, 12:21 AM
Abdelkader Ait Assou
Abdelkader Ait Assou - avatar
0
I/O parameters in Swift provide functionality to retain the parameter values even though its values are modified after the function call. At the beginning of the function parameter definition, 'inout' keyword is declared to retain the member values. It derives the keyword 'inout' since its values are passed 'in' to the function and its values are accessed and modified by its function body and it is returned back 'out' of the function to modify the original argument. func temp(inout a1: Int, inout b1: Int) { let t = a1 a1 = b1 b1 = t } var no = 2 var co = 10 temp(&no, &co) println("Swapped values are \(no), \(co)") When we run the above program using playground, we get the following result − Swapped values are 10, 2 Variables are only passed as an argument for in-out parameter since its values alone are modified inside and outside the function. Hence no need to declare strings and literals as in-out parameters. '&' before a variable name refers that we are passing the argument to the in-out parameter.
4th Sep 2016, 5:35 PM
Prashant
Prashant - avatar