Top 31 Swift Interview Questions

Top 31 Swift Interview Questions: Here are the top interview questions of Swift. Be prepared for the interview. You can download the entire questions in a pdf format. so guys All the best for your interview.

1) What is Swift? How is it different from Objective-C?

Swift and Objective-C both are used in iOS development but both are significantly different in terms of efficiency and usage.

  • Swift is an open-source programming language developed by Apple platform and expanded to build on Linus while Objective-C is not an open-source programming language and is limited to Apple.
  • Swift syntax is easy, clear and brief. It makes API’s easy to read and maintain while Objective-C is based on C language which is comparatively hard to use.
  • Swift is more rational and precise that’s why it has less number of code and easy to learn while Objective-C code is lengthy as double to Swift code.
  • Swift can be compiled as a dynamic framework while Objective-C cannot be compiled into static libraries and dynamic framework.

2) What is the meaning of question mark “?” in Swift?

In Swift, question mark “?” is used in the property declaration. It tells the compiler that this property is optional. The property may hold a value or not. It avoids runtime errors when accessing that property by using ?. This is useful in optional chaining and a variant of this example is in conditional clauses.

For example:

 var optionalName : String? = "John"  
if optionalName != nil {  
    print("Your name is \(optionalName!)")  
}   

3) How can you make a property optional in Swift?

We have to declare a question mark ??’ in the code to make a property optional. If a property doesn’t have a value, then the symbol? helps to avoid the runtime error.


4) What are the Half Open Range operators in Swift?

Swift supports several types of operators. One of them is the Half Open Range operator. The half-open range operator specifies a range between two values a and b (a<b) where b is not included. It is known as half open range operator because it contains its first value only not the final value.

You might like: Top 32 Selenium Interview Questions and Answers with PDF Download in 2019


5) What are functions in Swift?

Functions are the set of codes used to perform a specific task. In Swift programming language, functions are used to pass local as well as global parameter values inside the function’s call.

In Swift4, functions can be categorized in two types:

  • User Defined Functions
  • Built-in Functions (Library Functions)

6) Mention what are the type of integers does Swift have?

Swift provides unsigned and signed integers in 8, 16, 32 and 64-bit forms. Similar to C these integers follow a naming convention. For instance, an unsigned integer is denoted by type UInt8 while 32 bit signed integer will be denoted by type Int32.

7) Mention what is the Floating point numbers and what are the types of floating number in Swift?

Floating numbers are numbers with a fractional component, like 3.25169 and -238.21.  Floating point types can represent a wider range of values than integer types. There are two signed floating point number

  • Double: It represents a 64-bit floating point number, it is used when floating point values must be very large
  • Float: It represents a 32-bit floating point number, it is used when floating point values do not need 64-bit precision

8) Explain how multiple line comment can be written in swift?

Top 31 Swift Interview Questions Multiple line comment can be written as forward-slash followed by an asterisk (/*)  and end with an asterisk followed by a forward slash (*/).

9) What is de-initializer and how it is written in Swift?

A de-initializer is declared immediately before a class instance is de-allocated.  You write de-initializer with the deinit keyword.  De-initializer is written without any parenthesis, and it does not take any parameters. It is written as

deinit  {

// perform the deinitialization

}

10) Mention what are the collection types available in Swift?

In Swift, collection types come in two varieties Array and Dictionary

  • Array: You can create an Array of a single type or an array with multiple types. Swift usually prefers the former one

Example for single type array is,

 Var cardName : [String] = [ “Robert” , “Lisa” , “Kevin”]
 // Swift can infer [String] so we can also write it as:
 Var cardNames = [ “Robert”, “Lisa”, “Kevin”] // inferred as [String]
 To add an array you need to use the subscript println(CardNames[0]) 
  • Dictionary: It is similar to a Hash table as in other programming language. A dictionary enables you to store key-value pairs and access the value by providing the key
 var cards = [ “Robert”: 22, “Lisa” : 24, and “Kevin”: 26] 

11) List some control transfer statements used in Swift?

Some control statements are:

  • Control flow statements as the name suggests are efficient to check the course of execution in a program. There are several kinds of control transfer statements are present in Swift such as loop branch statement, loop statement, and control transfer statement
  • Loop branch permits a block of code to be executed time and again
  • Branch statements permit a particular block of code to be executed only if some circumstances are satisfied,
  • Control transfer statements present a method to change the system in which code is executed.

12) Explain the difference between let and var in Swift Programming?

Top 31 Swift Interview Questions Both the terms ‘let’ and ‘var’ is used for declaring the functions in JavaScript but the main difference between these two terms is that the ‘let’ is block scoped while a ‘var’ is the functional scope. It is not wrong to say that a variable represented with var is defined throughout the program in relation to let

Example of var:

Input: 
console.log(x); 
var x=5; 
console.log(x); 
Output: undefined 5

Example of let:

Input: 
console.log(x); 
let x=5; console.l
og(x); 
Output: Error

13) What is IOS Swift?

iOS swift is an intuitive and stalwart language for iOS. It is joyful to deal with the writing stuff in Swift. It is very advanced and its syntax is also concise and expressive too. It is very good by design and is able to produce software that runs very quick. It encompasses diverse modern hallmarks.

It is one of the programming languages and also a system creating an application for iOS and OS X.
For Cocoa and Cocoa touch, this programming language is considered to be an innovative one.

14) What is an in-out parameter in Swift?

In-out parameter lets you change the value of a function parameter from within the body of that function.

15) Distinguish between @synthesize and @dynamic in Objective –C?

  • @synthesize – It generates getter and setter methods for the property.
  • @dynamic – It notifies the compiler that the getter and setter are implemented at some other place.

16) What do you mean by Optional Chaining in Swift?

In Swift programming language, Optional Chaining is a process of querying and calling properties. You can chain multiple queries together, but if any link in the chain is nil then, the entire chain fails.


17) What is lazy stored procedure in Swift and when is it used?

Top 31 Swift Interview Questions Lazy stored properties are used for a property whose initial values are not calculated until the first time it is used. A lazy stored property can be declared by writing the lazy modifier before its declaration. Lazy properties are useful when the initial value for a property is reliant on outside factors whose values are unknown.


18) What is the usage of switch statement in Swift language?

  • Switch statement is used as a substitute for the long if-else-if statements.
  • Switch statement supports any type of data, synchronizes them and also checks for equality.
  • The break is not required in switch statement because there is no fall through in switch statement.
  • Switch statement must have covered all possible values for your variable.

19) What is the use of break statement in Swift language?

The break statement is used within a loop where you have to immediately terminate a statement. It is also used to terminate a case in a switch statement.


20) What is the use of continue statement in Swift loop?

The continue statement is used in Swift loop to change execution from its normal sequence. It stops currently executing the statement and starts again at the beginning of the next iteration through the loop.

21) What is the question mark ? in Swift?

The question mark ? is used during the declaration of a property, as it tells the compiler that this property is optional. The property may hold a value or not, in the latter case it’s possible to avoid runtime errors when accessing that property by using ?. This is useful in optional chaining (see below) and a variant of this example is in conditional clauses.

var optionalName : String? = “John"
if optionalName != nil {
    print(“Your name is \(optionalName!)”)
}

22) What is the use of double question marks ???

To provide a default value for a variable.

let missingName : String? = nil
let realName : String = “John Doe"
let existentName : String = missingName ?? realName

23) What is the use of exclamation mark !?

Top 31 Swift Interview Questions Highly related to the previous keywords, the ! is used to tell the compiler that I know definitely, this variable/constant contains a value and please use it (i.e. please unwrap the optional). From question 1, the block that executes the ifcondition is true and calls a forced unwrapping of the optional’s value. There is a method for avoiding forced unwrapping which we will cover below.

24) What is the difference between let and var in Swift?

The let keyword is used to declare constants while var is used for declaring variables.

let someConstant = 10
var someVariable : String

Here, we used the : string to explicitly declare that someVariable will hold a string. In practice, it’s rarely necessary — especially if the variable is given an initial value — as Swift will infer the type for you. It is a compile-time error trying to use a variable declared as a constant through let and later modifying that variable.

25) What is type aliasing in Swift?

This borrows very much from C/C++. It allows you to alias a type, which can be useful in many particular contexts.

typealias AudioSample = UInt16

26) What is the difference between functions and methods in Swift?

Both are functions in the same terms any programmer usually knows of it. That is, self-contained blocks of code ideally set to perform a specific task. Functions are globally scoped while methods belong to a certain type.

27) What are optional binding and optional chaining in Swift?

Optional bindings or chaining come in handy with properties that have been declared as optional. Consider this example:

class Student {
 var courses : [Course]?
}
let student = Student()

Optional chaining

If you were to access the courses property through an exclamation mark (!) , you would end up with a runtime error because it has not been initialized yet. Optional chaining lets you safely unwrap this value by placing a question mark (?), instead, after the property, and is a way of querying properties and methods on an optional that might contain nil. This can be regarded as an alternative to forced unwrapping.

Optional binding

Optional binding is a term used when you assign temporary variables from optionals in the first clause of an if or while block. Consider the code block below when the property courses have yet not been initialized. Instead of returning a runtime error, the block will gracefully continue execution.

if let courses = student.courses {
  print("Yep, courses we have")
}

The code above will continue since we have not initialized the courses array yet. Simply adding:

init() { courses = [Course]() }

Will then print out “Yep, courses we have.”

28) What’s the syntax for external parameters?

The external parameter precedes the local parameter name.

func yourFunction(externalParameterName localParameterName :Type, ....) { .... }

A concrete example of this would be:

func sendMessage(from name1 :String, to name2 :String) { print("Sending message from \(name1) to \(name2)") }

29) What is a deinitializer in Swift?

If you need to perform additional cleanup of your custom classes, it’s possible to define a block called deinit. The syntax is the following:

deinit { //Your statements for cleanup here }

Typically, this type of block is used when you have opened files or external connections and want to close them before your class is deallocated.

30) How should one handle errors in Swift?

Top 31 Swift Interview Questions The method for handling errors in Swift differ a bit from Objective-C. In Swift, it’s possible to declare that a function throws an error. It is, therefore, the caller’s responsibility to handle the error or propagate it. This is similar to how Java handles the situation.

You simply declare that a function can throw an error by appending the throwskeyword to the function name. Any function that calls such a method must call it from a try block.

func canThrowErrors() throws -> String

//How to call a method that throws an error
try canThrowErrors()

//Or specify it as an optional
let maybe = try? canThrowErrors()

Bonus question: What is a guard statement in Swift?

Guard statements are a nice little control flow statement that can be seen as a great addition if you’re into a defensive programming style (which you should!). It basically evaluates a boolean condition and proceeds with program execution if the evaluation is true. A guard statement always has an else clause, and it must exit the code block if it reaches there.

guard let courses = student.courses! else {
    return
}