Swi Interview Questions
struct student {
var myName: String
var myFriend: String
init(myName: String, myFriend: String) {
print("\(name) is being enrolled in class...")
self.myName = myName
self.myFriend = myFriend
}
}
22. How can we use the "inout" parameter in ios Swi ? Explain
with an example.
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 a er 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.
Page 21
© Copyright by Interviewbit
Swi Interview Questions
23. Explain the difference between Self and self in ios Swi .
There is a distinction between Self (capital S) and self (small S) when writing
protocols and protocol extensions. When used with a capital S, Self refers to the
protocol compliant type, such as String or Int. When used with a lowercase S, self
refers to the value contained within that type, such as "hi" or 999, for instance.
Consider the following SquareInteger extension as an example:
extension SquareInteger {
func squareANumber() -> Self {
return self * self
}
}
Page 22
© Copyright by Interviewbit
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: overhead
demoFunctionWithLessCopyOverhead(&ex)
// call by reference: no memory reallocation
Do'stlaringiz bilan baham: |