Swift Interview Questions

Be one of the shortlisted candidates with our sample Swift interview questions and answers. If you are looking to build your career as a Swift developer then prepare in advance with these frequently asked interview questions in Swift. These Swift interview questions and answers cover various topics like dump function, view model in MVVM and controller in MVC, etc. Be prepared and chase your dream job.

  • 4.6 Rating
  • 8 Question(s)
  • 10 Mins of Read
  • 5621 Reader(s)

Advanced

Use dependency injection to redesign the classes and provide data from test methods

protocol IBookStorage {
func fetchAllBooks()->[Book]
}
class BookStorage: IBookStorage  {
    func fetchAllBooks() -> [Book] {
        // return all available books
    }
}



 class BooksManager {
        let bookStorage:IBookStorage
        init(bookStorage:IBookStorage) {
            self.bookStorage = bookStorage
        }
        func physicsBooks() -> [Book] {
            let books = bookStorage.fetchAllBooks()
            // identify the physics book and return those
            let physicsbooks = …
            return physicsbooks
        }
    }
class StubBookStorage: IBookStorage  {
    var books = [Book]()
    init(books:[Book]) {
        self.books = books
    }
    func fetchAllBooks() -> [Book] {
        return books
    }
}
// Test methods
   func testBookManager() {
let books = …  // add stub data you want to test
let bookStorage = StubBookStorage(books: books)
let bookManager = BooksManager(bookStorage: bookStorage)
let physicsBooks = bookManager.physicsBooks()
// test the value physicsBooks array if correct
    }

Key is to use associated typeswhich is a powerful way of making protocols generic.

protocol Store {
    associatedtype DataType
    var ids: [DataType] { get set}
    mutating func add(id: DataType)
}
extension Store {
    mutating func add(id: DataType) {
        ids.append(id)
    }
}
struct SystemOne: Store {
    var ids = [String]()
}
struct SystemTwo: Store {
    var ids = [Int]()
}
var sysOne = SystemOne()
sysOne.add(id: "One")
sysOne.add(id: "Two")
var sysTwo = SystemTwo()
sysTwo.add(id: 1)
sysTwo.add(id: 2)
print(sysOne.ids)
print(sysTwo.ids)

In MVC, controller is coordinated that reads / saves data into the data model and displays data / handles actions in the view.

In MVVM, the view model is a close representation of a view. The view model is bound to the view. Any change in data in the view model, leads to notifiications and view pulls data from the view model and it displays it.

Test covering controllers can be a bit difficult as view is tightly attached to a view i.e View controller will have an instance of a view within it. So it will be difficult to mock the view methods called from the controller.

Test covering in  ViewModel is rather easy as it does not contain any reference to a view. Rather it only prepares data for the view only. It is the view that pulls the data from the view model.  Also, the view delegates the action to the View model. 

The derived class convenience initializers only and call convenience initializer or designated initializer of own class. Ultimately the call chain should have designated initializer at last of the same class.

So the correct code is :

class A {
    var name:String
    init(name:String) {
        self.name = name
    }
}
class B:A {
    var id : String
    init(name:String, id : String){
        self.id = id
        super.init(name: name)
    }
 convenience init (id:String) {
self.init(name: "unknown", id: id)
    }
}

Intermediate

It would provide a compilation error as  emp1 == emp2 cannot be resolved by compiler. It depends if the structs/classes are adapted to the Hashable protocol. The primitive data type like Int, String by default implement the Hashable protocol, show they do not show any error if we compare instances of such data types.

The corrected code would be:

struct Employee: Hashable {
    var name:String
    var  id:Int
    init(name:String, id:Int) {
        self.name = name
        self.id = id
    }
    var  hashValue: Int { return self.id}
}
The printed result would be true.

There will be a compilation error. The derived class Car calls the init method of superclass before its stored property, model gets initialised. Swift does 2 phase initialization, in first phase memory is allocated and all stored properties get initialized starting from the derived classes and then its superclass. Then in the second phase, all customizations of the properties are done, in the init method.

The correct code will be :

class Car:Transport {
    var model:String
    init(model:String){
        self.model = model
        super.init(type: "Car")
         self.model = "\(self.model) - type \(self.type)"
        print("\(self.model)")
    }
}
The result will be
  Transport - Car
   Maruti  - type Car

 Dump function is used to print the content of the object 

For eg: 

class Person {
    let name: String
    let cars: [String]?
    init(name:String, cars: [String]?) {
        self.name = name
        self.cars = cars
    }
}

let allPerson = [Person(name: "P1", cars: ["P1_C1", "P1_C2"]), Person(name: "P2", cars: ["P2_C1", "P2_C2"])]
dump(allPerson)

Output:

▿ 2 elements
  ▿ App.Person #0
    - name: "P1"
    ▿ cars: Optional(["P1_C1", "P1_C2"])
      ▿ some: 2 elements
        - "P1_C1"
        - "P1_C2"
  ▿ App.Person #1
    - name: "P2"
    ▿ cars: Optional(["P2_C1", "P2_C2"])
      ▿ some: 2 elements
        - "P2_C1"
        - "P2_C2"
//As seen, dump() outputs the whole class hierarchy, while print() simply outputs the class name.

DESCRIPTION

Swift is the latest, powerful and interactive programming language released by Apple. It is an interactive programming language which is safe and fast, also a fantastic way to develop software. Swift adopts a safe programming feature to make it simpler, easier. It is the first program that is expressive and enjoyable. And today, many people have started moving to Swift programming from Objective-c.

If you are a beginner looking to start your journey in programming and have dreams of building apps for iPhones, then Swift is the programming language one should definitely learn. Many businesses across the globe are putting efforts to have iOS apps, it means that if you have a strong Swift skill you will be in demand. Research says that the average salary for “swift developer” ranges from approximately $105,760 per year for a software engineer to $111. 899 per year for iOS Developer.

So, if you are a job seeker and looking forward to becoming a Swift developer then learning these Swift interview questions, and answers will be an added advantage. Test your knowledge! If you don’t know an answer, don’t worry each question has a solution.

These are some of the interview questions on Swift that can be helpful for you to crack the interview and to carry on your future in the programming industry. Swift Interview questions for experienced or freshers right here are curated by experts and will boost your knowledge and confidence.

We hope these basic interview questions on Swift will serve as a quick material to level up your preparation. You can also take up Master Swift training to advance your career. All the best!

Read More
Levels