Swift Interview Questions and Answers
by Nithyanandham, on Sep 11, 2022 6:09:46 PM
Q5. 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!)”)
}
Q7.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
Q8. 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.
Q9. 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
Q10. 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.
Q11. What is a double in Swift code?
Q13. 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 = 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.
Q14. 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 error
try canThrowErrors()
//Or specify it as an optional
let maybe = try? canThrowErrors()</pre>
Q15. 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)") }
Q16. 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.
Q17. What is swift compiled to?
Q18. 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.”