Sai krishna
Sep 3, 2018 · 12 min read

Swift Interview Questions

1) Diff between Swift and Objective C

Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C.

Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers, Doubleand Float for floating-point values, Bool for Boolean values, and String for textual data. Swift also provides powerful versions of the three primary collection types, Array, Set, and Dictionary.

1. Swift introduces advanced types not found in Objective-C, such as tuples (groupings of values.) You can use a tuple to return multiple values from a function as a single compound value.

2. Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. They work for any type, not just classes. Using optionals is similar to using nil with pointers in Objective-C

3. Swift is a type-safe language, If part of your code expects a String, type safety prevents you from passing it an Int by mistake.Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that expects a nonoptional String. Type safety helps you catch and fix errors as early as possible in the development process.

4. Swift is easier to read : no longer need semicolons to end lines or parenthesis,Method and function calls in Swift use the industry-standard comma-separated list of parameters within parentheses.Swift code more closely resembles natural English

5. Swift is easier to maintain : Swift combines the Objective-C header (.h) and implementation files (.m) into a single code file (.swift).

6. Swift is safer:

7. Swift is unified with memory management: in objective C its developer responsibility to manage memery handling whne working with lo level APIs like Core graphics.

Where as in Swift no need to think about memory management even in the low level APIs.

8. Swift requires less code

9. Swift is faster

10.Swift Playgrounds encourages interactive coding:Playgrounds enable programmers to test out a new algorithm or graphics routine, say 5 to 20 lines of code, without having to create an entire iPhone app.

2) Type Safe and Type inferring:

Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake.it performs type checks when compiling your code and flags any mismatched types as errors.

If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type.

Type inference is particularly useful when you declare a constant or variable with an initial value.

3) What is Type Aliases

Type aliases define an alternative name for an existing type. You define type aliases with the typealias keyword.

4) What is tuples:

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.

Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type.

5) What is Optionals:

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all.

NOTE: Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer — it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.

6) What is Forced unwrapping:

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

7) What is Optional Binding:

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable.

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false.

Write an optional binding for an if statement as follows:

if letconstantName= someOptional{……… }

if let tempVal1 = testNil, let tempVal2 = testNil1 , let testVal3 = testNil2 { }

8) Implicitly unwrapped optionals:

Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

let forcedOptional:Int? = 11

let implicitOptional:Int! = 12

print(forcedOptional!)

print(implicitOptional)

9) Optional Chaining:

Optional chaining is a Swift feature that allows execution of a statement to stop and return nil at any point.

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

Ex: superview?.gestureRecongnizers?.first

10)What is Nil coalescing operator:

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

use value A if you can, but if value A is nil then use value B.

It’s particularly helpful with optionals, because it effectively stops them from Being optional because you provide a non-optional value B. So, if A is optional and has a value, it gets used (we have a value.) If A is present and has no value, B gets used (so we still have a value). Either way, we definitely have a value.

let someValue = a ?? “DefaluleValue”

11)What is String interpolation:

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash (\):

12)Swift collections:

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.

A type must be hashable in order to be stored in a set — that is, the type must provide a way to compute a hash value for itself. A hash value is an Int value that is the same for all objects that compare equally, such that if a == b, it follows that a.hashValue == b.hashValue.

13)What is the use of guard? (early exit)

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause — the code inside the else clause is executed if the condition is not true.

14)Swift Functions:

Functions are self-contained chunks of code that perform a specific task.

func someFunction(argumentLabel parameterName: Int) { }

15)Variadic parameters:

A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (…) after the parameter’s type name.

Note: A function may have at most one variadic parameter.

16)InOut Parameters:

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

17)Closures:

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

18)Trailing Closures:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead.

19)Capturing values:

A closure can capture constants and variables from the surrounding context in which it is defined.

20)Escaping Closures:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

Swift’s closures are reference types, which means if you point two variables at the same closure they share that closure — Swift just remembers that there are two things relying on it by incrementing its reference count.

When a closure gets passed into a function to be used, Swift needs to know whether that function will get used immediately or whether it will be saved for use later on. If it’s used immediately, the compiler can skip adding one to its reference count because the closure will be run straight away then forgotten about. But if it’s used later — or even might be used later — Swift needs to add one to its reference count so that it won’t accidentally be destroyed.

21)AutoClosures:

An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.

22)What is Enumerations:

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

23)Recursive Enumerations:

A recursive enumeration is an enumeration that has another instance of the enumeration as the associated value for one or more of the enumeration cases. You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection.

24)Structures and Class difference:

Classes are reference types and Structures are value types

Structures are always copied when they are passed around in your code, and do not use reference counting.

All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create — and any value types they have as properties — are always copied when they are passed around in your code.

Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead.

25)Stored properties:

In its simplest form, a stored property is a constant or variable that is stored as part of an instance of a particular class or structure.

26)Lazy stored properties:

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

27)Computed properties:

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

28)Read only Computed properties:

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

29)Property Observers:

Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

· willSet is called just before the value is stored.

· didSet is called immediately after the new value is stored.

30)Type properties:

There will only ever be one copy of these properties, no matter how many instances of that type you create. These kinds of properties are called type properties.

31) Methods:

Instance Methods:Instance methods are methods that belongs to instance of a particular class.

Type Methods:You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.

In Objective-C, you can define type-level methods only for Objective-C classes. In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports.

32) Subscripts:

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key].

33) Prevent Override:

You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript).

34) ARC(Automatic reference counting:)

ARC automatically frees up the memory used by class instances when those instances are no longer needed.

35) Extensions:

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

36) Protocols:

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

37) Generics:

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

38) Access Control:

we have open, public, internal, fileprivate, and private for access control.Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.

Open and Public: Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module.

o public classes and class members can only be subclassed and overridden within the defining module (target).

o open classes and class members can be subclassed and overridden both within and outside the defining module (target).

  • Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

FilePrivate:functionality defined with a fileprivate access level can only be accessed from within the swift file where it is defined.

Private: You typically use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade