Swift Programming Interview Questions

1) Explain what is Swift Programming Language?

Swiftis a programming language and system for creating applications for iOS and OS X. It is an innovative programming language for Cocoa and Cocoa Touch.

2) Explain how you define variables in Swift language?

Variables and constants must be declared before they are used. You announce constants with the let keyword and variables with the var keyword. Both variables and dictionaries are described using brackets. For example,

Var  myTectra = “This is myTectra”

Let ksomeconstant = 30

3) Explain how Swift program is deployed?

Swift program deploys the application in a Tomcat installation by default. The deploy script bundles the client code into JavaScript, gathers all the server side classes required and packages them into file Hello.war. This file together with a GWT jar and a Swift runtime jar is copied into the Tomcat installation. If CATALINA_HOME is not set, these files require to be copied manually.

4) Mention what are the features of Swift Programming?

  • It eliminates entire classes of unsafe code
  • Variables are always initialized before use
  • Arrays and integers are checked for overflow
  • Memory is managed automatically
  • Instead of using “if” statement in conditional programming, swift has “switch” function

5) Mention what is the difference between Swift and ‘Objective-C’ language?

Difference between ‘C’ and ‘Swift’ language is that

Swift Objective-C
·In a swift, the variable and constants are declared before their use

·You have to use “let” keyword for constant and “var” keyword for variable

·There is no need to end code with semi-colon

·Concatenating strings is easy in swift and allows to make a new string from a mix of constants,  literals, variables, as well as expressions

·Swift does not require to create a separate interface like Objective C. You can define classes in a single file (.swift)

·Swift enables you to define methods in class, structure or enumeration

·In Swift, you use “ +=” Operator to add an item

·In objective C, you have to declare variable as NSString and constant as int

·In objective C, variable is declared as “ and constant as “

·The code ends with semi-colon

·In objective C, you have to choose between NSMutableString and NSString for string to be modified.

·For classes, you create separate interface (.h) and implementation (.m) files for classes

·Objective does not allow this

·In C, you use “addObject”: method of NSMutable array to append a new item to an array

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, unsigned integer is denoted by type UInt8 while 32 bit signed integer will be denoted by type Int32.

6) 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 does not need 64 bit precision

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

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

8) 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


9) 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]

10) List out what are the control transfer statements used in Swift?

Control transfer statements used in Swift includes

  • Continue
  • Break
  • Fallthrough
  • Return

11) Explain what is optional chaining?

Optional chaining is a process of querying and calling properties. Multiple queries can be chained together, and if any link in the chain is nil then, the entire chain fails.

12) How base-class is defined in Swift?

In Swift the classes are not inherited from the base class and the classes that you define without specifying its superclass, automatically becomes the base-class.

13) Explain what Lazy stored properties is and when it is useful?

Lazy stored properties are used for a property whose initial values is not calculated until the first time it is used.  You can declare a lazy stored property 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.

14) Mention what is the characteristics of Switch in Swift?

  • It supports any kind of data, and not only synchronize but also checks for equality
  • When a case is matched in switch, the program exists from the switch case and does not continue checking next cases. So you don’t need to explicitly break out the switch at the end of case
  • Switch statement must be exhaustive, which means that you have to cover all possible values for your variable
  • There is no fallthrough in switch statements and therefore break is not required

15)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!)”)}

16)What is the use of double question marks ???
To provide a default value for a variable.

let missingName : String? = nillet realName : String? = “John Doe”let existentName : String = missingName ?? realName

17)What is the use of exclamation mark !?
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 if condition 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.

18)What is the difference between let and var in Swift?</div>
The let keyword is used to declare constants while var is used for declaring variables.

let someConstant = 10var 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.

19)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

20)What is the difference between functions and methods in Swift?
Answer: 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.

21)What are optional binding and optional chaining in Swift?
Answer: 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.”

22) 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)”) }

23) What is a deinitializer in Swift?
Answer: 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.

24) How should one handle errors in Swift?
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 throws keyword 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 errortry canThrowErrors() //Or specify it as an optionallet maybe = try? canThrowErrors()</pre>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}

25)Consider the following code:

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

var array2 = array1


var len = array1.count

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

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.)

26)Consider the following code:

let op1: Int = 1

let op2: UInt = 2

let op3: Double = 3.34

var result = op1 + op2 + op3

Where is the error and why? How can it be fixed?

Swift doesn’t define any implicit cast between data types, even if they are conceptually almost identical (like UInt and Int).

To fix the error, rather than casting, an explicit conversion is required. In the sample code, all expression operands must be converted to a common same type, which in this case is Double:

var result = Double(op1) + Double(op2) + op3

27)The String struct doesn’t provide a count or length property or method to count the number of characters it contains. Instead a global countElements<T>() function is available. When applied to strings, what’s the complexity of the countElements function:

  • O(1)
  • O(n)

and why?

Swift strings support extended grapheme clusters. Each character stored in a string is a sequence of one or more unicode scalars that, when combined, produce a single human readable character. Since different characters can require different amounts of memory, and considering that an extreme grapheme cluster must be accessed sequentially in order to determine which character it represents, it’s not possible to know the number of characters contained in a string upfront, without traversing the entire string. For that reason, the complexity of the countElements function is O(n).

28)In Swift enumerations, what’s the difference between raw values and associated values?

Raw values are used to associate constant (literal) values to enum cases. The value type is part of the enum type, and each enum case must specify a unique raw value (duplicate values are not allowed).

The following example shows an enum with raw values of type Int:

enum IntEnum : Int {

case ONE = 1

case TWO = 2

case THREE = 3


An enum value can be converted to its raw value by using the rawValue property:

var enumVar: IntEnum = IntEnum.TWO

var rawValue: Int = enumVar.rawValue

A raw value can be converted to an enum instance by using a dedicated initializer:

var enumVar: IntEnum? = IntEnum(rawValue: 1)

Associated values are used to associate arbitrary data to a specific enum case. Each enum case can have zero or more associated values, declared as a tuple in the case definition:

enum AssociatedEnum {

case EMPTY

case WITH_INT(value: Int)

case WITH_TUPLE(value: Int, text: String, data: [Float])


Whereas the type(s) associated to a case are part of the enum declaration, the associated value(s) are instance specific, meaning that an enum case can have different associated values for different enum instances.

29)The following code snippet results in a compile time error:

struct IntStack {

var items = [Int]()

func add(x: Int) {

items.append(x) // Compile time error here.



30)Explain why a compile time error occurs. How can you fix it?

Structures are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, you can optionally allow such modification to occur by declaring the instance methods as ‘mutating’; e.g.:

struct IntStack {

var items = [Int]()

mutating func add(x: Int) {

items.append(x) // All good!



31)How to convert NSMutableArray to Swift Array in swift?

var myMutableArray = NSMutableArray(array: [“xcode”, “eclipse”, “net bins”])

​var myswiftArray = myMutableArray as NSArray as! [String]

 32)How to convert NSArray to NSMutableArray in swift?

We can convert the SwiftArray to a MutableArray by using the following code.

let myArray: NSArray = [“iOS”,”Android”,”PHP”]
var myMutableArray = NSMutableArray(array:myArray)


33)How to convert an array of characters into string in Swift without using any separator?

let SwiftCharacterArray: [Character] = [“a”, “b”, “c”, “d”]
let SwiftString = String(characterArray)


33.How to convert an array of Strings into a string in Swift without using any separator?

let SwiftStringArray = [“cocos2d”, “cocos2d-x”, “UIKit”]
let SwiftCharacterArray = SwiftStringArray.flatMap   { String.CharacterView($0) }
let SwiftString = String(SwiftCharacterArray)


34)How to convert an array of Strings into a string in Swift using space as separator?

let SwiftStringsArray = [“Model”, “View”, “Controller”]
let MySwiftString = SwiftStringsArray.joinWithSeparator(” “)print(MySwiftString)

35)How to convert an array of Strings into a string in Swift using separator?

let SwiftStringsArray = [“iPhone”, “iPad”, “iPod”]
let MySwiftString = SwiftStringsArray.joinWithSeparator(“,”)

36)How to convert Swift String into an Array?

let Ustring : String = “iOS Developer Questions”
let characters = Array(Ustring.characters)

Review Date
Reviewed Item
Good collection for preparing for an interview
Author Rating