Swift Interview Questions

Q – Introduce your past experience?

I have put this question here because this is the opening of any interview. Example:

I have extensive/good working experience on iOS app programming. I have worked on travel, chat, business, sports kind of apps. I have worked on UIKit, Foundation, Table View, Collection View, Core Data, Url session etc, Autolayout, Notification and In app purchase to name a few. I am also familiar with third party libraries like Alamofire, SDWebimage, AFNetworking etc. I am self starter, quick learner and team worker.

[relax]

Tell your over all experience, companies – recent two etc.

[relax]

Start talking about Most recent ¬†project, your responsibilities, challenges and end with it ūüôā

Note : You should know each and every thing written in your resume. So either you know what you wrote in your resume or just remove it.

Q – Difficulties when you want to use Swift things in Objective-C? Hint – Associated Enums, Tuples ūüôā
Q – Let’s say you have a json, how will you parse it? Hint – Codable

Answer –

Q – What are different ways to unwrap optionals?

Answer – 6 ways ūüôā

 

Q – What is difference between class function and static function in swift?

Answer-

Playground file for class vs static functions: https://bit.ly/2BsErB2

Q – What are defer and fallthrough?
Q – What are swift value and reference types?
Q – How to make sure that your singleton class is initialized once?
Q – In Xcode/Playground/online compiler Create a class Person and add two stored property personName, personAge. I want a conversation on different way of initialization?
Q – Few things you like and dislike about using Xcode?

Dislike

lacking (hanging = freezing)

sometimes auto-complete (Sometimes don’t get third-party libraries auto-complete)

Like

Auto-completion ‚Äď don‚Äôt need to remember the exact name or spelling

Instant result and fix ‚Äď able to find out the problem right away

Storyboard ‚Äď able to visualize UI flow

Easy to find out the documentation file

Q – How do you make a decision between using third party library and doing by yourself?
Q – What things do you take into consideration while merging code?
Q – What is your daily routine as a developer in office?
Q – Have you ever got conflicts? Most nightmare code conflict you ever encountered and how did you fixed it? (must talk about xcode conflict, storyboard conflict, talk real time experience)
Q – I have a app with sign in button, user clicked sign up but the app hanged what can be issue there?
Q – How you will parse xml based response? Codable? NSXmlParser ?
Q – How you will parse json based response? Codable?
Q – What do you mean by associated enum? What is optional? (this question is a hint, interviewer want to know if you know it or not optional are actually enum types)
Q – How to create a secure iOS app?

Considerations:

  • Use keychain to save sensitive data.
  • Communicate over Https.
  • Use http post body to transfer data over network, do not use query string or passing data in url.
  • Proper session handling like in banking apps, there must be single session of a user, you can not login from multiple deice with same credentials.
  • Make sure third party libraries are not stealing sensitive info.
  • Make sure public open source api are not sending critical data to their server.
Q – Give me example of pass by value and pass by reference in swift.

I am going to talk about copying objects in swift. Copying can be two ways‚Ää‚ÄĒ‚Ääcopy content (pass by value)¬†and¬†copy reference¬†(pass by reference).

Copy Content is also known as Deep Copy. Deep Copy works with value types. For example Structure, Array, Dictionary, Set, String etc.

Copy Reference is also known as shallow Copy. shallow Copy works with reference types. For example Classes.

Example of Deep Copy:

In above example we see that when we make deep copies, source (personObj) and destination(personObjAnother) objects have their own copies. Changes made to the newly copied objects does not impact source object.

  • Why Deep Copies¬†?

Deep copies are less prone to race conditions and suits well in multithreaded environment. You are sure the object on which you are performing changes will impact only same object. It will not make any impact on the source object. This is one of the reason also why apple have made collection types (Array, Dictionary, Set) as value types in Swift (which are reference types in Objective C).

Example of Shallow Copy:

 

In above example we see that when we make shallow copies, source (personObj) and destination(personObjAnother) objects have shared copies. Changes made to the newly copied objects does also impact source object.

  • Why Shallow Copies¬†?

Shallow copies are faster to create because sharing the reference only. The created copies does not entirely create new instance in memory instead only address/reference is copied.

Q – What are the advantages of Swift programming?

  1. Speed : Most of the types are struct example Array, Dictionary, Set, String Some of the examples. Struct are value types, passed by values, good choice for multithreading environment and memory safety(locks, mutex etc)
  2. The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free.
  3. Memory Management РFor classes ARC and for value type, the compiler will use traditional stack-based allocation, just as is done with most value types in languages such as C and its derivatives.
  4. Enums – So rich enum, have functions, raw and value types.
  5. Less Error-Prone: App crashes in Swift are appreciably lower as compared to Objective-C, because most of the errors caught at compile time, very less runtime issue to happen.
  6. Better Syntax: Easy, similar to python, kotlin, JS.
  7. Type Inference РAutomatic type detection based on r value like python.
  8. Type Safety : Strictly typed language, less error prone. Compare python is dynamic typed language
  9. Uses Copy on Write ? , My write up hare
  10. Swift is Functional, Protocol Oriented and object oriented Programming language.
  11. You are not sure about initial value of variables, use optionals.
  12. Server side swift with vapor, very very new, may be we see good in near future.
  13. Extension : I love it, add functions to existing classes at run time.
  14. Open-Source: Correct! A great apple swift community working on it.

The list can go on!

  • In what situations is Objective C a wiser option for a project than Swift?

Might be you want to use c, c++ based library. In this case you will have to use bridging header to work with swift.

Why used c, c++ ? Because there might be shared code/logic between apple, windows, android, blackberry.

  • Passing data from one VC to another VC, what design patterns we can follow to do that?

We can use push, present, segue, delegate, notification center etc

Q – class vs struct vs enums?

Q – How did you use MVVM in your project? Draw Architecture?

Q – NSURLSession¬†VS Alamofire diff? Hint –¬†Alamofire give callback on main queue, while URLSession gives callback on background queue.

Q – Delegate VS Notification Center vs block vs closure.

Q – How will you detect retain cycle and fix it?

Q – What is persistent and transient memory?

Persistent – current active instances of a class.

Transient – number of times a class have been deallocated or deinitialized.

Q – What are some latest changes in swift 4.2 or tell me about concepts:

Q – Agile?

Agile, is a process that helps teams provide quick and unpredictable responses to the feedback they receive on their project. 

Q – SearchController

Uses the SearchResultsUpdatingprotocol, along with NSComparisonPredicate, to filter out search results from the group of available products. NSComparisonPredicateis a foundation class that specifies how data should be fetched or filtered using search criteria.

Q – How to design universal application?

Adaptive UI

Size Classes

  • The Compact Size Class refers to a constrained space
  • The Regular Size Class refers to an expansive space.

The second concept is Auto Layout, which define the user interface using a series of constraints.

Q – NSCache ?

A mutable collection you use to temporarily store transient key-value pairs that are subject to eviction when resources are low.

Q – CocoaTouch Frameworks?

The Foundationframework provides a base layer of functionality for apps and frameworks, including data storage and persistence, text processing, date and time calculations, sorting and filtering, and networking.

The AVFoundationframework combines four major technology areas that together encompass a wide range of tasks for capturing, processing, synthesizing, controlling, importing and exporting audiovisual media on Apple platforms.

Q – Grand Central Dispatch (GCD)is a low-level API for managing concurrent operations.

Thread types: Main queue, background queue

Queue types:

Serial queue: First-In-First-Out

Pros:

  • Predictable Execution Order
  • Prevents Race Conditions

Concurrent queue:  Start at the same time

Pros:

  • Faster
  • Unpredictable Order

GCD, NSOperation and OQ Difference?

Q – Strong vs. Weak vs. Unowned?

Strong: Default. The child class exists as long as the parent exists.

Weak: Child may or may not exists. Will not exists if parent is removed from memory.

Unowned: Child definitely exists all the time but is removed when parent is removed.

When to use?

Weak: when the reference can become nil at some point in its lifetime

Unowned: When you know that the reference will never be nil once set.

Alamofireis an HTTP networking library written in Swift. It’s a layer on top of URLSession with the goal to make common networking features easier to implement.

BDD framework: Quick and Nimble

Quickis for writing testing cases structure and logic

Nimbleis pattern matching method

Q – New features of Swift?
  1. Random Number Generating
  2. CaseIterable For enumerations
  3. Toggle For Booleans
  4. Shuffle and Shuffled
  5. All Satisfy
  6. Dynamic Member Look Up
  7. Warning and Error Directives

 Remote Notification vs. Local Notification

Local notificationsare scheduled by the app and can be triggered by time, date or place.

Remote notificationson the other hand are sent by a backend. This can be your own backend, but also a cloud service you are using.

APNs workflow?

With push notification setup completely on your provider and in your app. Your provider can then send notification requests to APNs. APNs conveys corresponding notification payloads to each targeted device, and manage interactions with the user.

 Steps to setup APNs?

Step 1: Choose third party server

Step 2: Configure developer SSL certificate

Step 4: Go to project target capabilities in X Code and enable notification

Step 5: Export p12 from keychain

Step 6: Register the third party server with your p12 certificate

Step 7: Go to plist add ‚ÄėApp downloads content in response to push notifications‚Äô inside Required background modes

Step 8: Register notification in AppDelegate (requestAuthorization)

Step 3: Construct payload for each message

Step 9: Implement delegate methods (didRigisterForRemoteNotificationsWithDeviceToken, didFailToRegisterForRemoteNotificationsWithError)

Use Pusheror PushWizardfor APNs testing.

How to create an iOS APNs Certificate?

Step 1: Creating a CSR (Certificate Assistant ‚ÄúRequest a certificate‚ÄĚ) from your Keychain

Step 2: Downloading an APNs Certificate from your account
Step 3: Converting the .cer File to a .p12 Certificate.

Configure your app to process background updates notifications?

  1. Enable Background mode in project target capabilities
  2. Enable Remote Notification background mode

Payload

The payloadspecifies the types of user interactions (alert, sound or badge) that you want performed

Maximum payload size is 4KB, For Voice notifications 5KB

Before iOS 8 maximum payload size was 256 bytes.

Apple Pay (Using Stripe)- Integration

  • Create a Merchant ID
  • Configure Apple Pay capabilities in Xcode for the project
  • Create a sandbox user in iTunes Connect
  • Add a test card
  • Create a payment request in the project
  • Handle the result
  1. Add Apple PayCapabilities
  2. Add a merchant ID
  3. Create a Stripeaccount
  4. Create a certificate for Stripeto be able to process payments
  5. Get API key from Stripe
  6. Install Stripe cocoa pod
  7. Import Stripe in AppDelegate and register it with setDefaultPublishableKey
  8. Implement Apple Pay button by using class PKPaymentButton(trigger payments through Apple pay)
  9. Conform to protocol ‚ÄúPKPaymentAuthorizationViewControllerDelegate‚ÄĚ enabled by ‚ÄúcanMakePayments‚ÄĚ (PKPaymentSummaryItemcontains checkout items)
  10. PreparePKPaymentRequestfor PKPaymentAuthorizationViewController
  11. Handle completion in didAuthorizePaymentdelegate method.
  12. Dismiss window in paymentAuthorizationViewControllerDidFinish.

(PKPaymentNetwork used to choose payment method)

 Apple Pay РWorkflow

  1. Present the Apple Pay button
  2. Create the payment request
  3. Present the payment sheet
  4. Respond to charges by the user
  5. Submit payment information to payment gateway

Apple Pay – Security

When you add a credit/debit card to Apple Pay, information that you enter on your device is encrypted and sent to Apple servers. If camera, the information is never saved

Apple decrypts the data, determine your card’s payment network and re-encrypts the data with a key that only your payment network can unlock. 

Extension

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

Extensions in Swift can:

Add computed instance properties and computed type properties

Define instance methods and type methods

Provide new initializers

Define subscripts

Define and use new nested types

Make an existing type conform to a protocol

Computed Value? 

Implicitly unwrap vs. forced unwrap

Force Unwrap: It’s the action of extracting the value contained inside an Optional. I am sure this Optional value does contain a real value, extract it!

When we define an Implicitly unwrappedoptional, we define a container that will automatically perform a force unwrap each time we read it.

Class vs. struct

 Inheritance

Multi-level inheritance

UIButton Hierarchy

UIButton inherits from -> UIControl -> UIView -> UIResponsder -> NSObject

ViewController life cycle:

ViewDidLoad->ViewWillAppear->ViewDidAppear->ViewWillDisappear->ViewDidDisappear

Application life cycle:

Higher Order Functions in Swift – Array

Higher order functions are simply functions that operate on other functions by either taking a function as an argument, or returning a function.

Sorted take a closure or simply use sorted(by:).

Mapinstead of sorting it changes each element of the array based on the closure passed to the method.

Filterwill return an array that has only elements that pass your filter specified in your closure.

Reducefunction allows you to combine all the elements in an array and return an object of any type.

Flatmapflatten the 3 groups into one collection.

CompactMapis the map function but contains non-nil results.

Web Services (How to access)

We use web servicesto communicate with database. Web serviceis often a REST API that returns data in JSON (or XML) format.

REST(Representational State Transfer) is an approach to communications which makes simple HTTP calls for inter-machine communication. REST can be understood as a simple request/response mechanism.

REST is often preferred over SOAP(Simple Object Access Protocol) because REST does not use as much bandwidth as heavyweight SOAP does which makes it a better option for use over the Internet.

SOAP is a protocol REST is an architecture
SOAP can’t user REST because it is a protocol REST can user SOAP web services because it is a concept and can use any protocol like HTTP, SOAP
SOAP requires more bandwidth REST requires less bandwidth and resources
SOAP permits XML data format only REST permits different data format such as plain text, HTML, XML, JSON etc.
SOAP is less preferred than REST REST is more preferred than SOAP

Q – JSON Serialization, Codable, Decodable, Alamofire, AFNetworking.?

Questions And Answers – Core Data

I provide live iOS career counselling, app training, interview preparation using objective c or swift, in case you want complete iOS training can contact me on below details:

skype : alok.upadhyay32

mail : meiosdose@gmail.com

what‚Äôsapp¬†: +91‚Äď7838552946

  1. What is object graph in core data?
  2. What is core data?
  3. What is data persistance?
  4. What is core data stack?
  5. Give a example of data model?
  6. What are relationships in core data?
  7. What is abstract entity in core data?
  8. How to achieve Inheritance in core data entities?
  9. What is mainConcurrencyType?
  10. What is privateConcurrencyType?
  11. What is managed object context?
  12. How to create managed Object Context
  13. How to perform background task in core data
  14. Can we have more than one MOC
  15. Will you ever pass managedObject from one context to another context
  16. How to pass one managedObject from one context to other context
  17. What do you mean by thread safe
  18. What are different ways of creating private context
  19. How to write code for perform some long running task in background in core data
  20. What are core data delete rules
  21. What is NSAsynchronousFetchRequest
  22. How to set up NSAsynchronousFetchRequest
  23. How we can do multithreading with core data?
  24. How to transfer manage object from one thread to another thread?
  25. what is CoreData and what do we use it for
  26. is CoreData == sqlite or some wrapper?
  27. what types of stores does core data support
  28. What is the minimum necessary classes and relationship between them?
  29. Can the NSPersistentStoreCoordinator have more persistent stores?
  30. What is an NSManagedObjectId
  31. What is lazy initialization, how does this relate to core data, situations when this can be handy
  32. How to read only a few attributes of an entity
  33. What is a fetchedresultcontroller
  34. How to synchronize contexts
  35. How could one simulate an NSManagedObject (dynamic properties)
  36. What is relation
  37. what is insert command
  38. what is update command
  39. what is delete command
  40. persistant vs transient
  41. set up core data stack in iOS 9
  42. 5-6 points core data vs sqlite
  43. what is NSFetchResultController, will it block main UI
  44. When to do core data light weight migration all scenarios

Please support us by comment, like and share our facebook page.

Answers:

Object Graph

In¬†computer science, in an object-oriented program, groups of objects form a network through their relationships with each other‚ÄĒeither through a direct reference to another object or through a chain of intermediate references. These groups of objects are referred to as object graphs.

An object graph is a view of an object system at a particular point in time. 

Object-oriented applications contain complex webs of interrelated objects. Objects are linked to each other by one object either owning or containing another object or holding a reference to another object to which it sends messages. This web of objects is called an object graph.

Examples:

An array object that contains a single string object represents a small, simple object graph.

A group of objects containing an application object, with references to the windows, menus and their views, and other supporting objects, may represent a large, complex object graph.

Core Data

  1. ‚ÄúCore Data is a object graph management and persistence Framework‚ÄĚ. ‚ÄúCore Data is a framework that you use to manage the model layer objects in your application.It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.‚ÄĚ
  2. ‚ÄúCore Data is a model layer technology. Core Data helps you build the model layer that represents the state of your app. Core Data is also a persistent technology, in that it can persist the state of the model objects to disk.‚ÄĚ
  3. ‚ÄúCore Data’s focus is on objects rather than the traditional table-driven relational database approach. When storing data, you are actually storing an object’s contents, where an object is represented by an Objective-C/Swift class that inherits the NSManagedObject class. A typical application will have several objects used together, forming an object graph.‚ÄĚ
  4. Most imp point A Core Data consist of following stack objects:

    • a managed object model
    • a managed object context
    • a persistent store coordinator
    • a persistent store (storage)

Persistance Data

Save data in hard disk, so that it is available in multiple launched/ save data permanently.

Core Data Stack

A Core Data stack consist of following objects:

  • a managed object model
  • a managed object context
  • a persistent store coordinator
  • a persistent store (storage)

NSManagedObjectModel

  • An object that is an instance of NSManagedObjectModel. An NSManagedObjectModelobject describes a schema, a collection of entities (data models) that you use in your application. It uses a private internal store to maintain its properties and implements all the basic behavior required of a managed object.
  • The managed object model represents the data model of the application.¬†
  • An object that describes a schema‚ÄĒa collection of entities (data models) that you use in your application.
  • Even though Core Data isn’t a database, you can compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.
  • The¬†managed object model¬†is an instance of¬†NSManagedObjectModel¬†and describes the¬†schema used in your Core Data application. It is loaded from the¬†model file¬†which contains all the entity descriptions with their attributes and relationships that you defined in the Core Data Model inspector. So the model¬†describes¬†your objects.

Managed Object Context

A managed object should always be associated with a managed object context. There are no exceptions to this rule. Remember that a managed object context manages a number of records or managed objects.

Persistent Store Coordinator

The persistent store coordinator is the glue of the Core Data stack. It keeps a reference to the managed object model and the managed object context. And, as the name implies, the persistent store coordinator is in charge of the persistent store of the application.

A coordinator that associates persistent stores with a model (or a configuration of a model) and that mediates between the persistent stores and the managed object contexts.

Persistent Store Coordinator are actually the instances of “NSPersistentStoreCoordinator”¬†class.

Persistent store

A persistent store is a repository in which managed objects may be stored. You can think of a persistent store as a database data file where individual records each hold the last-saved values of a managed object. Core Data offers three native file types for a persistent store: binary, XML, and SQLite. From the above screen shot you can see persistent store coordinates with Persistent store coordinator.

Data Model

LIBRARY DATA MODEL

The Library entity has two attributes, name and location, both of type String. The Author entity also has two attributes, firstName and lastName, both of type String. The Book entity has three attributes, title of type String, publicationDate of type Date, and pages of type Integer 16. This is what the data model should look like in the data model graph.

Please support us by comment, like and share our facebook page.

RELATIONSHIPS

A relationship specifies the entity, or the parent entity, of the objects at the destination.

TO-ONE RELATIONSHIPS ‚ÄĒ>

A book belongs to a library. This means that we need to create a relationship that links a book to a library.

Steps :

  1. Open Library.xcdatamodeld and switch to the editor’s table style.
  2. Select the Book entity.
  3. Click the plus button at the bottom of the Relationships table to add a relationship to the entity.
  4. Set Relationship to library and Destination to the Library entity. Leave Inverse empty for now.
  5. Switch to the editor’s graph style to visual representation of the relationship we defined.

We can conclude below points :

  1. The relationship is to-one relationship.
  2. A book can belong to one library only.
  3. The single arrow is pointing from book entity to library entity.
  4. There is no arrow pointing back from Library to Book, so there is no inverse relationship. It means that the library the book belongs to does not know that the library belongs to this book.

How to make a relationship system where library knows what books it contains. We have following relationship :

INVERSE RELATIONSHIPS <‚ÄĒ->

Steps :

  1. Switch to editor’s table style and select the Library entity.
  2. Add a relationship named books.
  3. Set Destination to Book and set Inverse to library.

Switch to the data model graph to see what that looks like. The connection between Library and Book contains arrows pointing to and from each entity. See :

TO-MANY RELATIONSHIPS ‚ÄĒ>>

Ideally a library should have more than one books. Steps :

  1. Select the books relationship of the Library entity in the editor’s table style. Open the Data Model Inspector in the Utilities pane on the right to see the details of the relationship.
  2. In the Data Model Inspector, you can modify the relationship’s destination and inverse relationship. You can also modify the relationship’s type or cardinality. Core Data supports To-One and To-Many relationships. Set Type to To-Many.

Switch back to graph to see changes. The relationship from Library to Book now has two arrows, indicating that books is a to-many relationship.

MANY-TO-MANY RELATIONSHIPS <<‚ÄĒ>>

There might be a real word scenario where book/books can belong to many libraries. To fulfill this relationship we need to turn the library relationship into a to-many relationship.

Select the library relationship of the Book entity in the editor’s table style and set Type to To-Many in the Data Model Inspector.

For the best naming convention practices update the name of the relationship to libraries so that it is easily understood that a book can belong to multiple libraries.

This is what the data model graph looks like after the changes. The relationship that links the Library and Book entities is now a many-to-many relationship.

Very important note

The recommended approach is to model relationships in both directions and specify the inverse relationships appropriately. Core Data uses this information to ensure the consistency of the object graph if a change is made.

Reference of apple documentation

You might get this warning if you set no inverse relationship in Xcode:

warning: Misconfigured Property: Person.address should have an inverse

Fix

Just add a inverse relationship from Address to Person and warning is gone.

Add relationship from Address to Person(Destination) like this :

And finally it should look like this :).

Abstract Entities

Specify that an entity is abstract if you will not create any instances of that entity. You typically make an entity abstract if you have a number of entities that all represent specializations of (inherit from) a common entity that should not itself be instantiated. For example, in the Employee entity you could define Person as an abstract entity and specify that only concrete subentities (Employee and Customer) can be instantiated. By marking an entity as abstract in the Entity pane of the Data Model inspector, you are informing Core Data that it will never be instantiated directly.

An Entity can be abstract, in which case it is never directly attached to a managed object.

An abstract object (in programming) or entity (in Core Data) is an object or entity that is never instantiated.

Entity Inheritance

Entity inheritance works in a similar way to class inheritance; and is useful for the same reasons. If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity. Rather than specifying the same properties in several entities, you can define them in one entity, and the subentities inherit them. For example, you might define a Person entity with attributes firstName and lastName, and subentities Employee and Customer, which inherit those attributes. An example of this layout is shown in Figure 2-3. Display the layout diagram by clicking the Editor Style buttons in the lower-right corner.

In many cases, you also implement a custom class to correspond to the entity from which classes representing the subentities also inherit. Rather than implementing business logic common to all the entities several times over, you implement them in one place and they are inherited by the subclasses.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.