FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

27 Advanced Swift Interview Questions (SOLVED) iOS Developers Must Know

iOS devices makeup over 50% of the Australian mobile operating system market, and capture around the same market share in the US. And Swift as a skill and iOS Developer roles are intrinsically intertwined and according to ZipRecruiter, the average iOS Developer salary in the US in 2020 is $114,614 per year. Follow along and learn 27 advanced Swift interview questions (answered and solved) every experienced iOS Developer shall know before next tech interview.

Q1: 
What is the difference between Upcast and Downcast in Swift?

Answer
  • The upcast, going from a derived class to a base class, can be checked at compile time and will never fail.
  • However, downcasts can fail since you can’t always be sure about the specific class. If you have a UIView, it’s possible it’s a UITableView or maybe a UIButton.
    • downcasts must be either optional with as? or
    • “forced failable” with as! when sure about the type

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q2: 
What’s the difference between == and ===?

Answer
  • == operator checks if the values are the same, comparing value types. "equal to"
  • === operator checks if the references point the same instance (both point to the same memory address), comparing reference types. "identical to"

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q3: 
How to append one array to another array in Swift?

Problem

Consider:

var first = ["John", "Paul"]
let second = ["George", "Ringo"]

How to append one array to another array in Swift? Note: the first array mutable so we can join the second array to it.

Answer
  • One option for joining arrays is the append(contentsOf:) method, used like this:

    first.append(contentsOf: second)
  • Another option is using the += operator, which is overloaded for arrays to combine elements:

    first += second
  • The third option is to use a regular + to create a new array by combining two others:

    let third = first + second

All three options produce the same resulting array.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q4: 
How to break out of multiple loop levels?

Problem

Consider:

let numbers = 1...100

for number1 in numbers {
    for number2 in numbers {
        if number1 == number2 && number1 * number2 == 144 {
            print("Square found: \(number1)")
        }
    }
}

How to exit both loops as soon as the correct number 144 is found?

Answer

Consider:

outerLoop: for number1 in numbers {
    for number2 in numbers {
        if number1 == number2 && number1 * number2 == 144 {
            print("Square found: \(number1)")
            break outerLoop
        }
    }
}

Notice the outerLoop: before the for number1 loop, and also the matching break outerLoop – that will cause both loops to exit as soon as the correct number is found.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q5: 
Rewrite this code in a Swift way

Problem

Consider:

let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()

for (index, element) in list.enumerated() {
    arrayOfTuples += [(index, element)]
}

print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

Can you rewrite this code in a more "swiftier" way?

Answer

Yeap, the way to do it is:

let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]

or with map:

let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q6: 
What Classes and Structs have in common in Swift and what are their differences?

Answer

The features classes and structs have in common:

  • Both structs and classes can define properties to store values, and they can define functions
  • They can define subscripts to provide access to values with subscript syntax
  • They can define initializers to set up their initial state, with init()
  • They can be extended with extension (this is important!)
  • They can conform to protocols, for example to support Protocol Oriented Programming
  • They can work with generics to provide flexible and reusable types

Classes support a few more capabilities that structs don’t have:

  • Classes can inherit from another class, like you inherit from UIViewController to create your own view controller subclass
  • Classes can be deinitialized, i.e. you can invoke a deinit() function before the class is destroyed
  • Classes are reference types and structs are value types
    • Value Type: When you copy a value type (i.e., when it’s assigned, initialized or passed into a function), each instance keeps a unique copy of the data. If you change one instance, the other doesn’t change too.
    • Reference Type: When you copy a reference type, each instance shares the data. The reference itself is copied, but not the data it references. When you change one, the other changes too.

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q7: 
What does the Swift mutating keyword mean?

Answer

Being the value type structs are immutable. Meaning other variables can not change the values for instance of structure at any given point.

The mutating word is required for changing the values of self variables inside structure's function only.

For. e.g

struct MyStruct {
    var abc: String = "initila value"

    func changeValue() {
        abc = "some other value". //Compile time error: Cannot assign to property: 'self' is immutable. Mark method 'mutating' to make 'self' mutable.
    }
}

Here as we are trying to change value of variable abc inside function declared in struct itself, we get the compile time error.

So here we need to make function mutating to make change value inside structure. Hence the correct code will be:

struct MyStruct {
    var abc: String = "initila value"

    mutating func changeValue() {
        abc = "some other value"
   }
}

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q8: 
What is trailing closure syntax?

Answer

Many functions in iOS accept multiple parameters where the final parameter is a closure. Trailing closure syntax is a little piece of syntactic sugar that makes particularly common code more pleasant to read and write.

Consider:

func greetThenRunClosure(name: String, closure: () -> ()) {
    print("Hello, \(name)!")
    closure()
}

Use:

greetThenRunClosure(name: "Paul") {
    print("The closure was run")
}

This functionality is available wherever a closure is the final parameter to a function.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
What is a good use case for an inout parameter?

Answer

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.

inout means that modifying the local variable will also modify the passed-in parameters. Without it, the passed-in parameters will remain the same value. Trying to think of reference type when you are using inout and value type without using it.

  1. A good use case will be swap function that it will modify the passed-in parameters.
  2. Consider removing the overhead of copying as well. If you have a function that takes a somewhat memory-wise large value type as argument (say, a large structure type) and that returns the same type, and finally where the function return is always used just to replace the caller argument, then inout is to prefer as associated function parameter.
struct MyStruct {
    private var myInt: Int = 1

    // ... lots and lots of stored properties

    mutating func increaseMyInt() {
        myInt += 1
    }
}

/* call to function _copies_ argument to function property 'myHugeStruct' (copy 1)
   function property is mutated
   function returns a copy of mutated property to caller (copy 2) */
func myFunc(var myHugeStruct: MyStruct) -> MyStruct {
    myHugeStruct.increaseMyInt()
    return myHugeStruct
}

/* call-by-reference, no value copy overhead due to inout opimization */
func myFuncWithLessCopyOverhead(inout myHugeStruct: MyStruct) {
    myHugeStruct.increaseMyInt()
}

var a = MyStruct()
a = myFunc(a) // copy, copy: overhead
myFuncWithLessCopyOverhead(&a) // call by reference: no memory reallocation

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q10: 
What is difference between as?, as! and as in Swift?

Answer
  • In Swift 1.2 and later, as can only be used for upcasting (or disambiguation) and pattern matching:
// 'as' for pattern matching
switch item {
case let obj as MyObject:
    // this code will be executed if item is of type MyObject
case let other as SomethingElse:
    // this code will be executed if item is of type SomethingElse
...
}
  • as? produces an optional value, which is either the value if it can be cast to the specified type, or nil if it can't.
  • as! doesn't produce an optional, it just produces a value of the specified type, and if the cast fails, it aborts the program. Saying foo as! SomeType is basically the same thing as saying (foo as? SomeType)! (except you get a better error message).

You should only ever use as! if you're 100% certain the cast will succeed (because if you're wrong, the whole program aborts).


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q11: 
What's the difference between Self vs self?

Answer

When you’re writing protocols and protocol extensions, there’s a difference between Self (capital S) and self (lowercase S). When used with a capital S, Self refers to the type that conform to the protocol, e.g. String or Int. When used with a lowercase S, self refers to the value inside that type, e.g. “hello” or 556.

As an example, consider this extension on BinaryInteger:

extension BinaryInteger {
    func squared() -> Self {
        return self * self
    }
}

Remember, Self with a capital S refers to whatever type is conforming to the protocol. In the example above, Int conforms to BinaryInteger, so when called on Int the method returns an Int.

On the other hand, self with a lowercase S refers to whatever value the type holds. If the example above were called on an Int storing the value 5 it would effectively be 5 * 5.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q12: 
What’s the difference between a protocol and a class in Swift?

Answer

In their basic form, a protocol describes what an unknown type of object can do. You might say it has two or three properties of various types, plus methods. But that protocol never includes anything inside the methods, or provides actual storage for the properties.

In a more advanced form, you can write extensions on your protocols that provide default implementations of the methods. You still can’t provide storage for properties, however.

In comparison, classes are concrete things. While they might adopt protocols – i.e., say they implement the required properties and methods – they aren’t required to do that. You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q13: 
When to use strong, weak and unowned references?

Answer
  • To determine if you even need to worry about strong, weak, or unowned, ask, “Am I dealing with reference types”. If you’re working with Structs or Enums, ARC isn’t managing the memory for those Types and you don’t even need to worry about specifying weak or unowned for those constants or variables.
  • Strong references are fine in hierarchical relationships where the parent references the child, but not vice-versa. In fact, strong references are the most appropraite kind of reference most of the time.
  • When two instances are optionally related to one another, make sure that one of those instances holds a weak reference to the other.
  • When two instances are related in such a way that one of the instances can’t exist without the other, the instance with the mandatory dependency needs to hold an unowned reference to the other instance.


Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q14: 
When to use a set rather than an array in Swift?

Answer

You should use a set rather than an array if all the following criteria are true:

  1. You intend to add each item only once. Sets never allow duplicates.
  2. You don’t care about the order of the items in the set.
  3. You don’t need to use APIs that require arrays.
  4. You’re storing Hashable types, either your own or one of Swift’s built-in types likes strings and integers. Sets use hash values for fast look up of items.

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions

Q15: 
When would you use self in a method?

Answer

By far the most common reason for using self is inside an initializer, where your likely to want parameter names that match the property names of your type, like this:

struct Student {
    var name: String
    var bestFriend: String

    init(name: String, bestFriend: String) {
        print("Enrolling \(name) in class…")
        self.name = name
        self.bestFriend = bestFriend
    }
}

Having Tech or Coding Interview? Check 👉 72 Swift Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
Can you rewrite this code using mutating function?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q17: 
Explain when to use different Swift casting operators?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q18: 
Explain the difference between weak and unowned references. Provide an example.

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q19: 
Is there a way to create an abstract class in Swift?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q20: 
What is Copy on Write (Cow) in Swift?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q21: 
What is the difference between fileprivate and private?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q22: 
What is the difference between open and public keywords in Swift?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
What to use: [String: Any] or [String: AnyObject]?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q24: 
What's wrong with this code?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q25: 
What’s the difference between Any and AnyObject?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q26: 
What is the use of Hashable protocol?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q27: 
What’s the difference between init?() and init()?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...