Consider the following code:

var array1 = [1, 2, 3, 4, 5]

var array2 = array1

array2.append(6)

var len = array1.count

What’s the value of the len variable, and why?



Consider the following code: var array1 = [1, 2, 3, 4, 5] var array2 = array1 array2.append..

Answer / iosraj

The len variable is equal to 5, meaning that array1 has 5 elements, whereas array2 has 6 elements:

array1 = [1, 2, 3, 4, 5]

array2 = [1, 2, 3, 4, 5, 6]

When array1 is assigned to array2, a copy of array1 is actually created and assigned.

The reason is that swift arrays are value types (implemented as structs) and not reference types (i.e. classes). When a value type is assigned to a variable, passed as argument to a function or method, or otherwise moved around, a copy of it is actually created and assigned or passed. Note that swift dictionaries are also value types, implemented as structs.

Value types in swift are:

structs (incl. arrays and dictionaries)

enumerations

basic data types (boolean, integer, float, etc.)

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Apple iOS Swift Interview Questions

What is block in swift?

0 Answers  


struct Planet { var name: String var distanceFromSun: Double } let planets = [ Planet(name: "Mercury", distanceFromSun: 0.387), Planet(name: "Venus", distanceFromSun: 0.722), Planet(name: "Earth", distanceFromSun: 1.0), Planet(name: "Mars", distanceFromSun: 1.52), Planet(name: "Jupiter", distanceFromSun: 5.20), Planet(name: "Saturn", distanceFromSun: 9.58), Planet(name: "Uranus", distanceFromSun: 19.2), Planet(name: "Neptune", distanceFromSun: 30.1) ] let result1 = planets.map { $0.name } let result2 = planets.reduce(0) { $0 + $1.distanceFromSun } What are the types and values of the result1 and result2 variables? Explain why.

1 Answers  


Is swift open source?

0 Answers  


Explain how you define variables in Swift language?

1 Answers  


How do you make a bridging header in swift?

0 Answers  






Is swift an object-oriented programming language?

0 Answers  


What is the difference between array and nsarray?

0 Answers  


Is ios written in swift?

0 Answers  


What are the half open range operators in swift?

0 Answers  


What are swift categories?

0 Answers  


What is the latest version of swfit programming?

0 Answers  


Explain the common execution states for a swift ios app (ios application lifecycle).

0 Answers  


Categories