1.

How can we use the "inout" parameter in ios Swift? Explain with an example.

Answer»

By default, function parameters are constants. CHANGING the value of a function parameter from within the function's body causes a compile-time error. Modifying the local variable also modifies the passed in arguments, which is KNOWN as the "inout" parameter. The passed-in arguments will have the same value if it is not present. Trying to remember the reference type while using inout and the value type when not using it. The SWAP function, which modifies the parameters handed in, is an excellent example. Consider REDUCING the copying overhead as well. If you have a function that takes a memory-intensive large value type as an argument (say, a huge structure type) and returns the same type, and the function return is only used to replace the caller argument, the inout parameter is the associated function parameter to use. As we can see in the example given below, a CALL to the function "demoFunction" copies arguments to function property 'aBigStruct'(copy 1) and the function property is mutated after which, the function returns a copy of the mutated property to the caller (copy 2). However, in the function "demoFunctionWithLessCopyOverhead", call by reference is being done and zero value copy overhead is there because of the usage of inout optimization.

struct demoStruct { private var counter: Int = 1 // ... a lot of stored properties mutating func incrementCounter() { counter += 1 }}/* call to this function copies argument to function property 'aBigStruct'(copy 1) function property is mutated function returns a copy of mutated property to caller (copy 2) */func demoFunction(var aBigStruct: MyStruct) -> MyStruct { aBigStruct.incrementCounter() return aBigStruct}/* call by reference -> zero value copy overhead because of the inout optimization */func demoFunctionWithLessCopyOverhead(inout aBigStruct: MyStruct) { aBigStruct.incrementCounter()}var ex = MyStruct()ex = demoFunction(ex) // copy, copy: overheaddemoFunctionWithLessCopyOverhead(&ex) // call by reference: no memory reallocation


Discussion

No Comment Found