Swift Interview Questions and Answers

Question 7. What is “??” in swift? Why it is used?

Answer 7. “??” in swift is called nil coalescing operator. Nil coalescing operator unwraps an optional and returns its value and returns a default value in case optional contains no value.

let name = (self.userName ?? "admin")   // if the optional property userNmae does not contain any value admin is returned.

Question 8. How to create a array in swift with default values?

Answer 8. In swift Array with default values can be created by providing default value and array length in constructor

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

Question 9. How are Array and Dictionary in swift different from NSString , NSDictionary and NSArray? 

Answer 9Array,Dictionary and string in swift are structure implementation and thus they have all the basic difference of a class and structure like

  • Classes can be inherited.
  • Classes can have more then one reference.
  • Classes can have Deinitializers .

Swift language guide states that

In Swift, many basic data types such as StringArray, and Dictionary are implemented as structures. This means that data such as strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.

This behavior is different from Foundation: NSStringNSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.

But the copy behavior is for us and we should always take it as that. Under the hood swift avoids copying the structures till it is absolutely necessary and does pass them by reference.

A pat on the back !!