Swi Interview Questions
35. Let us take into consideration the following code snippet in
ios Swi :
struct Course{
var toughness: Int = 3
}
var courseOne = Course()
var courseTwo = courseOne
courseTwo.toughness = 4
What will be the respective values of courseOne.toughness and
courseTwo.toughness? If Course was a class instead of a struct, would the values
be any different?
The value of courseOne.toughness will be 3 and the value of courseTwo.toughness
will be 4 if Course is a structure since Structures in ios Swi
are value types and the
following line just copies the courseOne to courseTwo by value and not by reference:
var courseTwo = courseOne
If Course was a class instead of a struct, then the above given line would copy
courseOne to courseTwo by reference and therefore, the values of both courseOne
and courseTwo would be 4 by the end of the code snippet as they have the same
address. Classes in ios Swi are Reference types therefore both the given courses
have the same address.
36. In the given code snippet, we have used var to declare
viewOne and let to create viewTwo. Will the last line
compile?
import UIKit
var viewOne = UIView()
viewOne.alpha = 0.7
let viewTwo = UIView()
viewTwo.alpha = 0.7 // Does this line compile?
Page 30
© Copyright by Interviewbit
Swi Interview Questions
The last line will, in fact, compile. viewOne is a variable that we can reassign to a new
UIView object. Because we can only assign a value once with let, the following code
will not compile:
viewTwo = viewOne // Error: viewTwo is immutable
However, because UIView is a reference-based class, we can change the properties of
viewTwo — which means the following code will compile:
let viewTwo = UIView()
viewTwo.alpha = 0.7 // Yes, this compiles!
Do'stlaringiz bilan baham: