Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ios Interview QA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

iOS Interview Questions

1. How to make code thread safe in swi . (Objc - Using atomic and Swi - Proprty wrapper
with lock unlock.)
2. How to download and save thousands of data and reload to UI.
https://developer.apple.com/documentation/coredata/
loading_and_displaying_a_large_data_feed
3. 1 array is accessing same me from two thread then what happened? If crashes then how
to resolved.
4. what is single responsibility principle.
https://clean-swift.com/single-responsibility-principle-for-class/

Key Points for iOS Development.

• Design pa erns all in deep


• Core data
• No ca ons
• Frameworks - Sta c and Dynamic
• Swi .
• Security
• Oops concepts
• AutoLayout
• Unit Tes ng
• GIT , SVN
• CICD - CI-(Github, svn, etch version tools) CD: (Genkins, circle ci, fast lane to deliver
build, Testl ghts)
• OBJ C
• Cocoa-pods and Carthage
• Mul Threading - GCD and NSOpera ons
• API, NSUrlSession.
• Resume Study.

# iPhone SDK:
A so ware development kit (SDK) released by Apple that allows people to write applica ons
for both the iPhone and the iPod Touch. The iPhone SDK includes the Xcode IDE,
Instruments, iPhone simulator, frameworks and samples, compilers, Shark analysis tool, and
more.

1. NSArray VS Array

⁃ Array is a struct, therefore it is a value type in


Swift. 

ti
ft
ti
ft
fi

ti
ti

tt

fi

ti

ti

ti
ft

ft
ti
⁃ NSArray is an immutable Objective C class,
therefore it is a reference type in Swift

⁃ and it is bridged
to Array<AnyObject>. NSMutableArray is the
mutable subclass of NSArray.

1. NSString VS String

⁃ While String and NSString are mostly
interchangeable,

⁃ NSString : Creates objects that resides in heap and


always passed by reference.

⁃ String: Its a value type whenever we pass it , its


passed by value. like Struct and Enum, String itself
a Struct in Swift.

⁃ String is automatically bridged to Objective-C as


NSString.

⁃ From Swift 4 -> Strings Are Collection Of


Characters.

⁃ Now String is capable of performing all operations


which anyone can perform on Collection type.

Q : What is Abstraction
Concepts : This is one of the concepts of OOPs
Definition : It mean hiding the complexity of class
Example : Working of car engine is hide from the user

What is new in iOS 13 for notification Example Token ?


https://nshipster.com/apns-device-tokens/

Bindable values in Swift


https://www.swiftbysundell.com/articles/bindable-values-in-swift/

Abstraction
https://cocoacasts.com/how-to-create-an-abstract-class-in-swift

Animation
https://www.yudiz.com/uiview-animation-with-swift-4/

● Data binding in MVVM between to classes?


● Why delegate is weak? – Ans - because we retain cycle should not happen.
● What is semaphore
● What are HTTP status code in with error?
● Enums with Associated Values
● How to create a custom OptionSet in enum ?
● What is indirect in enum?
● Why Swift is protocol oriented language ?
● What is IS & Has relationship in OOP?
● Why multiple inheritance is not allowed in swift ?
● How to achieve multiple inheritance in swift ? Ans- (through protocols)
● What is SOLID principle ?
● What is Race conditions?
● Why multiple inheritance is not supported in swift?
● What is Virtual function? - (It’s mainly used in dynamic polymorphism and can be
use in C++ only)
● How to cache
● What is loosely coupled architecture?
● What is separation of concerns and programming to an interface.? (https://
agostini.tech/2017/03/27/using-dependency-injection/)

Abstraction Encapsulation
Abstraction solves the problem and issues Encapsulation solves the problem and issue
that arise at the design stage. that arise at the implementation stage.
Abstract class is incomplete class This is complete or Concrete class

Abstraction is about hiding unwanted details Encapsulation means hiding the code and
while giving out most essential details data into a single unit

Exp: In other words, Abstraction means Exp: Class or method to protect the inner
extracting common details or generalizing workings of an object from the outside world.
things
Abstraction lets you focus on what the object Encapsulation means hiding the internal
does instead of how it does details of how an object works. When you
keep internal working details private, you can
change it later with a better method
Abstraction allows you to focus on what the Encapsulation enables you to hide the code
object does instead of how it does it and data into a single unit to secure the data
from the outside world.

Focus mainly on what should be done. Focus primarily on how it should be done.
Abstraction is the method of hiding the Whereas encapsulation is a method to
unwanted information. hide the data in a single entity or unit
along with a method to protect
information from outside.
In Swift we can implement abstraction Whereas encapsulation we can
using protocol implement using access modifier i.n.
private and public.
Abstraction is used to hiding something too Encapsulate hides variables or some
but in a higher degree(class, implementation that may be changed so often
protocol(interface) ). in a class to prevent outsiders access it directly.
They must access it via getter and setter
Clients use an abstract class(or interface) do methods.
not care about who or which it was, they just
need to know what it can do.
Example = When you first describe an Encapsulation is all about implementation. Its
object, you talk in more abstract term e.g. a sole purpose is to hide internal working of
Vehicle which can move, you don't tell how
Vehicle will move, whether it will move by objects from the outside world so that you
using tires or it will fly or it will sell. It just can change it later without impacting outside
moves. This is called Abstraction. We are clients
talking about a most essential thing,
which is moving, rather than focusing on For example, we have a HashMap which
details like moving in plane, sky, or water. allows you to store the object using put()
method and retrieve the object using the get()
There are also different levels of Abstraction
and it's good practice that classes should method. How HashMap Implements this
interact with other classes with the same level method (see here) is an internal detail of
of abstraction or higher level of abstraction. As HashMap, the client only cares that put stores
you increase the level of Abstraction, things the object and get return it back, they are not
start getting simpler and simpler because you
leave out details. concerned whether HashMap is using an
array, how it is resolving the collision,
whether it is using linked list or binary
tree to store object landing on same bucket
etc.

https://javarevisited.blogspot.com/2017/04/difference-between-abstraction-and-
encapsulation-in-java-oop.html

❖ What is SOLID Principle?


❖ Ref: https://medium.com/@vinodhswamy/solid-principles-in-swift-7dc2b793fd68
Description Summary Example

Single Each an every class you Each an every class should have Normal
Responsibil create/change should have only one responsibility Class
ity only one responsibility
Principle
Open Close Classes and Modules should Should not modify the existing Extensions
Principle be open for extension but class for change requirement,
closed for modification rather extent the class
Liskov Child classes should never Extending or Inheriting a child/ Inheritance
substitution break the parent class type derived class should not break
principle definitions any parent or base class
functionality
Interface Make fine grained interfaces The Interface or class API’s to Protocol
Segregation that are client specific client should have minimum
Principle information required by the client
Dependenc High level modules should Class A should not depend on Cocoa pods
y Inversion not depend on low level Class B or vice versa, both should Carthage
Principle modules both should depend be loosely coupled
on Abstractions

❖ What is Adaptive Layout?


❖ https://rshankar.com/beginners-tutorial-adaptive-layout-ios/

Adaptive Layout was introduced in iOS 8 to address the problem of designing user interfaces
for different devices and screen sizes.
In the earlier version of iOS, we had to maintain different storyboards for iPad and iPhone
and with Adaptive Layout we just needed a storyboard for all the devices.
Some of the main components of Adaptive Layout are Auto Layout, Size Classes and
Trait Collections.
Let us try to understand Adaptive Layout by designing the following user interface for
various devices and screen sizes.

❖ What is dependency Injection and its types?


❖ https://medium.com/@JoyceMatos/dependency-injection-in-
swift-87c748a167be

Dependency Injection is a technique where you would inject dependencies into an object.
Dependency Injection mean It’s just another Object that our class need to function

Types of Dependency Injection

● Property Injection
● Constructor Injection
● Method Injection

Property Injection
class LibraryViewModel {
var library = Library?
}
let libraryViewModel = LibraryViewModel()
let library = Library()
libraryViewModel.library = library

Here have the same view model object, but now it is no longer responsible for creating
its own dependency. In this particular example, the dependency is injected into the
LibraryViewModel via the library property and it receiving it from the outside. This kind of
dependency injection is called property injection.

Constructor Injection
class LibraryViewModel {
var library: Library
init(library: Library) {
self.library = library
}
}

Another way to implement dependency injection is through its constructor, or


initializer. A constructor injection is another type of dependency injection where the
dependency is injected into an object right at its inception — the initializer.

Method Injection

protocol LibraryManager {
func deleteAllBooks(in library: Library)
}

class DataManager {
func serializeRequest(request: Request, withSerializer serializer: Serializer) -> Data? {
}
}



Next we have method injection, and if you’re guessing that this is where we inject
dependencies through our methods, you are correct! Here is an example of method injection at
play.

❖ What is autorelease pool in ios?


❖ http://www.ioslearners.com/2017/03/06/swift-memory-management-
autorelease-pool/
Swift Memory Management: Autorelease Pool
Autorelease pool blocks provide a mechanism whereby you can give up ownership of
an object, but avoid the possibility of it being deallocated immediately (such as when you
return an object from a method). A drain operation of that pool will happen at the end of every
main run loop. This kind of delay-release is necessary in development, sometimes we will want
a variable lives longer than its scope (such as a callee function), so we can keep using it later.

In Swift, UIApplicationMain handles the application’s autorelease pool & we don’t have
to use autorelease by our self. But in some special cases we might need to add our own
autorelease pool.

Where to use autorelease pool?


Consider the scenario where you need to process a number of images in a loop.
func processDirectory(){
if let path = NSBundle.mainBundle().pathForResource("directory", ofType: "txt") {
for i in 1...90000
{
let data = NSData.dataWithContentsOfFile(path, options: nil, error: nil)
self.processData()
}
}
}

Here we are using data variable of significant size in a loop. This may take a lot of
device’s memories. To optimize this code we can add autorelease pool as follows:

func processDirectory(){
if let path = NSBundle.mainBundle().pathForResource("directory", ofType: "txt") {
for i in 1...90000{
autoreleasepool {
let data = NSData.dataWithContentsOfFile(path, options: nil, error: nil)
self.processData()
}
}
}

}
Here we are using data in autorelease pool, which gets drained with each iteration of the
for loop when for loop’s scope ends. As releasing the small chunk of memory in each loop may
cause performance issues, we can further optimize it to use autorelease pool in every n
iterations instead of each iteration.
Swift does its memory management very efficiently and does not recommend to
use autorelease.
Still having knowledge of autorelease & using it wisely can help you app to avoid
memory leaks.

❖ What is HTTP status code in with error?


https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

1) Informational responses (100–199)


2) Successful responses (200–299),
3) Redirects (300–399),
4) Client errors (400–499),
5) Server errors (500–599)

200 OK
201 Created
202 Accepted
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
500 Internal Server Error

What is Grand Central Dispatch (GCD)?


❖ https://www.youtube.com/watch?v=iTcq6L-PaDQ
❖ https://medium.com/@nimjea/grand-central-dispatch-in-swift-fdfdd8b22d52
❖ https://theswiftdev.com/2018/07/10/ultimate-grand-central-dispatch-tutorial-in-swift/
❖ https://medium.com/@aliakhtar_16369/concurrency-in-swift-operations-and-operation-
queue-part-3-a108fbe27d61
❖ https://medium.com/flawless-app-stories/parallel-programming-with-swift-
operations-54cbefaf3cb0
❖ https://marcosantadev.com/4-ways-pass-data-operations-swift/https://marcosantadev.com/
4-ways-pass-data-operations-swift/
❖ https://medium.com/@aliakhtar_16369/concurrency-in-swift-
operations-and-operation-queue-part-3-a108fbe27d61

❖ What is Tasks, Threads and Processes?


Before going further, there are a few technical concepts you need to understand. Here are some
key terms:
● Task: a simple, single piece of work that needs to be done.
● Thread: a mechanism provided by the operating system that allows multiple sets of
instructions to operate at the same time within a single application.
● Process: an executable chunk of code, which can be made up of multiple threads.

❖ There are two types of thread


1. Main Thread (User Interactive)
2. Background Thread
1. User Initiated (HIGH)
2. Default (DEFAULT)
3. Utility ( LOW)
4. Background ( BACKGROUND)

❖ There are Three types of QUEUE


1. Serial Queue
2. Concurrent Queue
3. Parallel Queue

Serial Concurrent Parallel Queue


Queue Queue
Use to perform task Use to perform task Use to perform task
synchronously Asynchronously Asynchronously

concurrency is a program- A parallel program is one that


structuring technique in uses a multiplicity of
which there are multiple computational hardware (e.g.,
threads of control. several processor cores) to
Conceptually, the threads perform a computation more
of control execute “at the quickly. The aim is to arrive at
same time”; that is, the the answer earlier, by
user sees their effects delegating different parts
interleaved. Whether they of the computation to
actually execute at the different processors that
same time or not is an execute at the same time.
implementation detail; a
concurrent program
can execute on a single
processor through
interleaved execution
or on multiple physical
processors

❖ Grand Central Dispatch or GCD


● GCD is a low-level API for managing concurrent operations.
● It will make your application smooth and more responsive and also helps for improving
application performance
● Sometimes we are trying to perform multiple tasks at the same time that time most of the
developer-facing application hang or freezing issue this is a common issue.
● That’s why we are using GCD to manage multiple tasks at the same time.

❖ What is an operation in Swift?


● An Operation is typically responsible for a single synchronous task.
● It’s an abstract class and never used directly.
● You can make use of the system-defined BlockOperation subclass or by creating your own
subclass.
● You can start an operation by adding it to an OperationQueue or by manually calling the
start method. However, it’s highly recommended to give full responsibility to the
OperationQueue to manage the state

Operation States
● isReady
● isExecuting
● isFinished
● isCancelled

Benefits of Operation Queues Over GCD


● Operations can be paused, resumed, and cancelled. Once you dispatch a task using
GCD, you no longer have control or insight into the execution of that task.
● The NSOperation API is more flexible in that respect, giving the developer control over
the operation’s life cycle
● The Operation API provides support for dependencies. You can create complex
dependencies between tasks very easily though in GCD you can achieve it but you have
to do a lot of work
● NSOperation and NSOperationQueue classes have a number of properties that
can be observed, using KVO (Key Value Observing). This is another important
benefit if you want to monitor the state of an operation or operation queue.
● The NSOperationQueue also adds a number of benefits to the mix. For example, you
can specify the maximum number of queued operations that can run simultaneously.
This makes it easy to control how many operations run at the same time or to create a
serial operation queue

There are mainly three ways to create operations


1. BlockOperation (Concrete Class)
2. NSInvocationOperation (Concrete Class) (Only in Objective-C)
3. Custom Operations

1) BlockOperation (Concrete Class)


A class you use as-is to execute one or more block objects concurrently.
Because it can execute more than one block, a block operation object operates using a group
semantic; only when all of the associated blocks have finished executing is the operation itself
considered finished
Example:
let printerOperation = BlockOperation()
printerOperation.name = "Print"
printerOperation.queuePriority = .normal //veryLow, low, normal, high, veryHigh

printerOperation.addExecutionBlock { print("I") }
printerOperation.addExecutionBlock { print("am") }

printerOperation.completionBlock = {
print("I'm done printing")
}

let operationQueue = OperationQueue()


operationQueue.qualityOfService = .userInteractive
operationQueue.maxConcurrentOperationCount = 2
operationQueue.addOperation(printerOperation) //Start Running

2) NSInvocationOperation (Concrete Class)









A class you use as-is to create an operation object based on an object and selector from
your application.
In objective C we can create NSInvocationOperation while it’s not available in
Swift.

Example:
@implementation MyCustomClass
- (NSOperation *) taskWithData: (id) data {
NSInvocationOperation *Op = [[NSInvocationOperation alloc] initWithTarget: self
selector: @selector(myTaskMethod :) object: data];
return Op;
}

// This is the method that does the actual work of the task.
- (void) myTaskMethod: (id) data {
// Perform the task.
}
@end

3) Custom Operations
Subclassing Operation gives you complete control over the implementation of your
own operations, including the ability to alter the default way in which your operation executes
and reports its status

❖ What is QualityOfService in operation?


● Used to indicate the nature and importance of work to the system. Work with higher quality
of service classes receive more resources than work with lower quality of service classes
whenever there is resource contention
● This property specifies the service level applied to operation objects added to the
queue
● If the operation object has an explicit service level set, that value is used instead.
The default value of this property depends on how you created the queue. For
queues you create yourself, the default value is
NSOperationQualityOfServiceBackground. For the queue returned by the main
method, the default value is NSOperationQualityOfServiceUserInteractive and
cannot be changed.

https://www.allaboutswift.com/dev/2016/5/21/gcd-with-qos-in-swift

Types of QualityOfService




● User Interactive
All UI related tasks need to be assigned that QoS class. It basically tells iOS to
run them on the main thread.
● User Initiated
This is the class to choose if a task is triggered by the user but doesn't have to be
run necessarily on the main thread.
● Default
This class is only listed for informational purposes only. The system defaults to
this class when not enough information is available to determine QoS.
● Utility
This class needs to be chosen for tasks that have a dependency on other system
resources like file I/O or network I/O. Those tasks need to wait for a certain
amount of time before they are able to complete. They are always in one way or
another initiated by the user who waits for their completion.
● Background
This class is supposed to be used for maintenance tasks - Tasks that don't depend
on their fast execution and that are oblivious to the user.

● Grand Central dispatch (Multi threading concept) GCD is a library that provides a low-
level and object-based API to run tasks concurrently while managing threads behind the
scenes. Terminology
● Dispatch Queues:- A dispatch queue is responsible for executing a task in the first-in,
first-out order
● Serial Dispatch Queue :- A serial dispatch queue runs tasks one at a time.
● Concurrent Dispatch Queue:- A concurrent dispatch queue runs as many tasks as it can
without waiting for the started tasks to finish.
● Main Dispatch Queue:- A globally available serial queue that executes tasks on the
application’s main thread.

8.1)NSOperation — NSOperationQueue — 
NSBlockOperation?
https://www.appcoda.com/ios-concurrency/
NSOperation :- Adds a little extra overhead
compared to GCD, but we can add
dependency among various operations and re-use, cancel or suspend them





NSOperationQueue:- It allows a pool of threads to be created and used to execute


NSOperations in parallel. Operation queues aren’t part of GCD

NSBlockOperation :- Allows you to create an NSOperation from one or more


closures. NSBlockOperations can have multiple blocks, that run concurrentl

NSOPERATION:
https://medium.com/shakuro/nsoperation-and-nsoperationqueue-to-improve-concurrency-in-
ios-e31ee79c98ef

Diifrence between GCD and NSOperation


https://cocoacasts.com/choosing-between-nsoperation-and-grand-central-dispatch/
===================================================================
OOP’s
===================================================================
===

❖ What is Value and Reference types?


All the data types in Swift broadly fall into two categories, namely value types and
reference type
● Value type — each instance keeps a unique copy of its data. Data types that
fall into this category include — all the basic data types, struct, enum, array,
tuples.
● Reference type — instances share a single copy of the data, and the type
is usually de ned as a class, closure

❖ Difference between structure and class


❖ Ref:
● https://www.quora.com/What-is-the-difference-between-class-and-structure
● https://www.apptamin.com/blog/app-store-optimization-aso-app-name-and-keywords/
● https://www.codementor.io/mattgoldspink/ios-interview-tips-questions-answers-objective-
c-du1088nfb

Class Structure
Class is a reference type and its Structure is a value type hence
object is created on Heap its object is created on Stack
memory. memory.

Class can inherit another Can not inherit another class or


class. Struct.

fi
s

Example:
 Int,String,
Class, Functions and Double,Array,Set,Dictionary,
closer Struct, Enum and Tuple
Class can have a constructor Structure can only have the
and destructor of all types. parameterized constructor. it
means a structure can not have
the non-parameterized
constructor,the default
constructor and destructor also.
The member variable can be The member variable cannot be
initialized directly. initialized directly.
We can call diinit in class We can not call diinit in struct
Object of class can be let if Object of struct should be var if
you want to change the value you want to change the value of
of property property
ARC will the object of class ARC is not work on Value type
if object reference count is
zero
Note: Stack is used for static memory allocation and Heap for dynamic memory
allocation, both stored in the computer’s RAM

❖ What is shallow and deep copy?


❖ shallow Copy works with reference types. Example Classes, Closure
❖ Deep Copy works with value types. Example Structure, Array, Dictionary, Set,
String

❖ What is negative testing?


❖ Provided invalid data while Testing application (Example: Enter text in mobile
number text eld )
❖ Test the negative scenarios.

===================================================================
===
SWIFT
===================================================================
===

❖ Swift language is Static type?


❖ Yes , It is static type
❖ The compiler must have all information about all classes and functions at compile
time.

fi

❖ You can "extend" an existing class (with an extension), but even then you
must define completely at compile time what that extension consists of.
Ref : https://stackoverflow.com/questions/29924477/is-swift-a-dynamic-or-static-language
Objective-C:
Objective-C is dynamic, and since, in real life, you will probably be using Swift in the
presence of Cocoa, you can use the Objective-C runtime to inject / swizzle methods in a Swift class
that is exposed to Objective-C
You can do this even though you are speaking in the Swift language. But Swift itself is
static, and in fact is explicitly designed in order to minimize or eliminate the use of Objective-C-
type dynamism.

❖ What is Static or Static variable/function ?


● Only object/Copy created for static variable/function and that will be shared
among all the object
● We can access variable/Function from class name only
● We can not override the static variable/function in subclass.

https://www.hackingwithswift.com/example-code/language/whats-the-difference-
between-a-static-variable-and-a-class-variable

❖ What is the difference between a static variable and a class variable?


Both the static and class keywords allow us to attach variables to a class
rather than to instances of a class. For example, you might create a Student class
with properties such as name and age, then create a static numberOfStudents
property that is owned by the Student class itself rather than individual instances

Where static and class differ is how they support inheritance: When you make a
static property it becomes owned by the class and cannot be changed by
subclasses, whereas when you use class it may be overridden if needed.

For example, here’s a Person class with one static property and one class
property

class Person {
static var count: Int {
return 250
}
class var averageAge: Double {
return 30
}
}
If we created a Student class by inheriting from Person, trying to override count (the static
property) would fail to compile if uncommented, whereas trying to override averageAge (the class
property) is OK:
class Student: Person {
// THIS ISN'T ALLOWED
// override static var count: Int {
// return 150
// }
// THIS IS ALLOWED
override class var averageAge: Double {

return 19.5
}
}

❖ What is type of initializer in swift


Initialization is the process of preparing an instance of a class, structure, or
enumeration for use. This process involves setting an initial value for each stored
property on that instance and performing any other setup or initialization that is
required before the new instance is ready for use

You implement this initialization process by de ning initializers, which are like
special methods that can be called to create a new instance of a particular type.
Unlike Objective-C initializers, Swift initializers do not return a value. Their primary
role is to ensure that new instances of a type are correctly initialized before they are
used for the rst time

Instances of class types can also implement an initializer, which performs any
custom cleanup just before an instance of that class is deallocated. For more
information about deinitializers, see Deinitialization.

Swift de nes two types of initializers for class types to help ensure all stored
properties receive an initial value. These are known as designated initializers and
convenience initializers.
Designated initializers and deinitializers must always be provided by the
original class implementation.

Ans: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

1) Default Initializers
Swift provides a default initializer for any class or structure that provides default
values for all of its properties and does not provide at least one initializer itself. The
default initializer simply creates a new instance with all of its properties set to their
default values.
Exp:
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()

fi
fi

fi
.

2) Designated Initializers (Initializer Delegation for Value Types)

Initializers can call other initializers to perform part of an instance’s


initialization. This process, known as initializer delegation, avoids duplicating
code across multiple initializers.

init(parameters) {
statements
}

3) Convenience Initializers
● Convenience Initializers give me an easy way to create a speci c type of
Object
● Convenience Initializers is optional and create an object and present the value
of Property of Clas
● Convenience Initializers must call default or designated initialize
convenience init(parameters) {
self.init()
}

https://www.youtube.com/watch?v=LxKZf0LyRbA
https://medium.com/@abhimuralidharan/initializers-in-swift-part-1-intro-convenience-and-
designated-intializers-9adf5632fb52

4) Failable Initializers
https://www.youtube.com/watch?v=RXnCNQBLiEQ

init?(age:Int) {
if age < 0 {
return nil
}
}

5) Memberwise Initializers for Structure Types


Structure types automatically receive a memberwise initializer if they don’t
de ne any of their own custom initializers. Unlike a default initializer, the structure
receives a memberwise initializer even if it has stored properties that don’t have
default values
Failable initializer use when we don’t want to create an object of class or Struct
if input value is incorrec
If Input value is incorrect it will return nil and It also work in inheritanc
Ans:
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)

6) Required Initializers

fi

fi
r

Write the required modi er before the de nition of a class initializer to indicate
that every subclass of the class must implement that initializer:
class SomeClass {
required init() {
// initializer implementation goes here
}}

You must also write the required modi er before every subclass implementation
of a required initializer, to indicate that the initializer requirement applies to further
subclasses in the chain. You do not write the override modi er when overriding a
required designated initializer
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes
here
}
}

❖ What is Optional binding ?


❖ Optional binding mean unwrapping the optional value using if Let or Guard

var userName:String?
userName = "Value"
//if let
if let name = userName {
print(name)
}

//Guard
func getName()->String?{
guard let name = userName else { return nil }
return name
}

getName()

❖ What is optional chaining?


❖ Optional chaining is a process for calling or querying properties, methods, and
subscripts
❖ If the optional contains a value, the property, method, or subscript get call
❖ If the optional is nil, the property, method, or subscript call returns nil
❖ Multiple queries can be chained together,
❖ Chain fails gracefully if any link in the chain is nil.
Ref

fi

fi

fi

fi

● https://www.youtube.com/watch?v=9fa3tNZcNJU
● https://www.youtube.com/watch?v=ZL8BFK8bVjk

❖ What is a Subscript ?
❖ Subscripts are used to store and retrieve the values without the use of
separate method with the help of index
❖ To access elements via subscripts write one or more values between square
brackets after the instance name
Re
● https://medium.com/@abhimuralidharan/subscripts-in-swift-51e73cc5ddb5
Example:

class Sample {
private var days = ["One", "Two" , "Three"]
subscript(index: Int) -> String {
get {
return days[index]
}
set(newValue) {
self.days[index] = newValue
}
}
}
var p = Sample()
print(p[0]) // prints One
p[0] = "Monday"
print(p[0]) // prints Monday

struct subexample {
let decrementer: Int
subscript(index: Int) -> Int {
return decrementer / index
}
}

let division = subexample(decrementer: 100)


print("The number is divisible by \(division[9]) times")
print("The number is divisible by \(division[2]) times")

❖ What is Upcasting and Downcasting and What is Optional?


❖ Below video contains all things related to protocols and upcast downcast etc.
Ref
● https://www.youtube.com/watch?v=yN0cRMZrdjc

❖ What is Store property?


❖ Stored property can be stored as part of an instance of a class or structure.
❖ Stored properties can only use by classes and structures
❖ Stored property can be constant or variable
❖ Stored properties can be either variable stored properties (introduced by the var
keyword) or constant stored properties (introduced by the let keyword)
❖ Store properties can be declared as var and let ( Constant )

❖ What is Computed property?


❖ Computed properties don’t have a stored value. So each time you call a
computed property, the value needs to be calculated
❖ Computed Properties compute the value by providing a getter and an optional
setter to retrieve and set other properties and values indirectly rather than storing
values directly
❖ Computed properties are provided by classes, structures, and enumerations
❖ In addition to stored properties, classes, structures, and enumerations can de ne
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.
❖ Computed properties including read only computed properties must be declared
as var and not as let ( Constant ).

enum Mobile:Int
case iPhone =
case Android =
var name:String
return "Os "

let ggg = Mobile.init(rawValue: 1


print(ggg?.name

Ref: https://docs.swift.org/swift-book/LanguageGuide/Properties.html

❖ What is Lazy property?


❖ If a stored property with a default value is marked with the keyword lazy
❖ Default value will not be initialized immediately until the property is
called for the very first time.
❖ So if the property gets never called, it will never be initialized.
❖ You could use this feature for example, if the initialization is expensive in
terms of memory or CPU usag
❖ You can’t use lazy with let
❖ You can’t use it with computed properties . Because, a computed
property returns the value every time we try to access it after executing
the code inside the computation block.
❖ You can use lazy only with members of struct and class
❖ Lazy variables are not initialised atomically and so is not thread safe.
Ref
● https://medium.com/@abhimuralidharan/lazy-var-in-ios-swift-96c75cb8a13a

Example
class TestClass
lazy var testString: String =
print("about to initialize the property"
}

fi

return "TestString
}(

let testClass = TestClass(


print("before rst call"
print(testClass.testString
print(testClass.testString

Weak Unowned
If Property can be nil then we will use If Property can not be nil then we will
weak use Unowned
We can set nil value to it We can’t set nil value
It must be Var It can be Var or Constant
Weak alway be an optional Unowned always be Non-Optional

❖ What is static property?


https://www.hackingwithswift.com/example-code/language/whats-the-
difference-between-a-static-variable-and-a-class-variable

❖ Both the static and class keywords allow us to attach variables to a class
rather than to instances of a class.
❖ Create a Student class with properties such as name and age, then
create a static numberOfStudents property that is owned by the Student
class itself rather than individual instances
❖ Where static and class differ is how they support inheritance
❖ When you make a static property it becomes owned by the class and
cannot be changed by subclasses, whereas when you use class it may
be overridden if needed
❖ Type properties are part of a type but not of an instance – also known as
static properties.
❖ Both stored and computed properties can be type properties. For that, you
use the keyword static

❖ What is associated value in enum?

Example
}

fi

"

enum Work{
case start
case InProgress
case Finish
case status(total:Int,done:Int)
}
let task = Work.status(total: 10, done: 7)

Access Associated values


switch task {
case .start: break
case .InProgress: break
case .Finish: break
case .status(let total, let done):
print("Ans = ",total, done)
break
}
Output = Ans = 10 7

❖ What is indirect in Enum?


● To use recursive enum we use indirect key word in enum
● Indirect enums are enums that need to reference themselves
● Somehow, and are called “indirect” because they modify the way Swift stores them
so they can grow to any size.
● Without the indirection, any enum that referenced itself could potentially become
in nitely sized: it could contain itself again and again, which wouldn’t be possible.

Example :
indirect enum LinkedListItem<T> {
case endPoint(value: T)
case linkNode(value: T, next: LinkedListItem)
}

let third = LinkedListItem.endPoint(value: "Third")


let second = LinkedListItem.linkNode(value: "Second", next: third)
let first = LinkedListItem.linkNode(value: "First", next: second)

var currentNode = first

listLoop: while true {


switch currentNode {
case .endPoint(let value):
print(value)
break listLoop

fi

case .linkNode(let value, let next):


print(value)
currentNode = next
}
}

Ref:
https://www.hackingwithswift.com/example-code/language/what-are-indirect-enums
===================================================================
===

❖ What is a communication patterns ?


❖ Communication pattern mean two classes can communicate with other
There are two ways to doing it
1. Delegate (using protocol) (KVC) (One to One Communication)
2. Noti cation Observers (KVO) (One to Many Communication)

Ref:
● https://www.youtube.com/watch?v=DBWu6TnhLeY
● https://www.tutorialspoint.com/objective_c/objective_c_protocols.htm
● https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/
ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html

❖ What is a Cocoa Design Patterns ?


❖ A design pattern provides a general reusable solution for the common problems
❖ Adopt and incorporate with Cocoa design patterns in your Swift apps

Design Patterns:
1 KVO (Key-Value Observing) in Swift
Notify objects about changes to the properties of other objects.
2 Delegates ( to Customize Object Behavior)
Respond to events on behalf of a delegator.
3.Singleton (Managing a Shared Resource Using a Singleton)
Provide access to a shared resource using a single, shared class instance.
4.Build-Up pattern
Ans:
5.Protocol
Ans:
Architecture:

fi

● MVC
● MVVM
● MVP -
● VIPER

https://developer.apple.com/documentation/swift/cocoa_design_patterns#topics
https://www.youtube.com/watch?v=qb05nLPYKz8
https://www.raywenderlich.com/477-design-patterns-on-ios-using-swift-part-1-2
https://medium.com/@saad.eloulladi/ios-swift-mvp-architecture-pattern-a2b0c2d310a3
https://www.cs.colorado.edu/~kena/classes/5448/f12/presentation-materials/myrose.pdf
https://www.youtube.com/watch?v=VcoZJ88d-vM

❖ What is a delegate ?
❖ Delegate is communication pattern through which two classes can communicate
with each other
❖ Delegate is used for one to one communication
❖ Delegate use protocols to create a relationship between two classes
❖ Using delegate you can return something back

❖ What is a Notification and Observers ?


❖ Noti cation is communication pattern through which two or more classes can
communicate with each other
❖ Noti cation is used for one to many communication
❖ Noti cation user observers to achieve this

❖ What is a KVC and KVO ?


❖ KVC - Key Value Coding
● To achieve this we use Delegate communication pattern using protocol 

And collection type which is Dictionary
● Stands for Key-Value Coding. It’s a mechanism by which an object’s
properties can be accessed using string at runtime rather than having to
statically know the property names at development time

❖ KVO - Key Value Observer


● To achieve this we use Noti cation observer
● Stands for Key-Value Observing and allows a controller or class to observe
changes to a property value. In KVO, an object can ask to be noti ed of any
changes to a speci c property, whenever that property changes value, the
observer is automatically noti ed.
● Property observers are declared as a variable and not as constants because it
is only a mutable property that can be tracked by property observers.
● Hence, property observers are declared with var and not the let keyword.

Ref:
● https://medium.com/@rguruonline/swift-computed-properties-and-property-
observers-56374675c9e2
fi
fi
fi

fi

fi

fi

fi

● https://medium.com/the-andela-way/property-observers-didset-and-willset-
in-swift-4-c3730f26b1e9
● https://www.appcoda.com/understanding-key-value-observing-coding/

❖ Types of size classes?


❖ The two Size Classes that exist currently are Compact and Regular.
❖ In iOS, Size Classes are groups of screen sizes that are applied to the width and
height of the device screen. The Compact Size Class refers to a constrained
space. It is denoted in Xcode as wC (Compact width) and hC (Compact height)
❖ The Regular Size Class refers to a non-constrained space. It is denoted in Xcode
as wR (Regular width) and hR (Regular height).

● Width Any Height Any


This is for all device in Portrait and landscape mode
● Regular Width Regular Height
This is for iPad in both Mode
● CompactWidth RegulorHeight
This is all iPhone in Portrait Mode
● CompactHeight
This is for all iPhone in landscape mode

https://www.bignerdranch.com/blog/designing-for-size-classes-in-ios/

❖ What is property Observer?


❖ willSet and didSet

❖ What is “dispatch_once” ?
❖ Is dispatch only one time, this is used when we initialize singleton class once.

❖ Difference between Any and AnyObject?


❖ Ref:https://medium.com/@mimicatcodes/any-vs-anyobject-in-
swift-3-b1a8d3a02e00
❖Any can represent an instance of any type at all, including
optional and function types.
❖ AnyObject can represent an instance of any class type.

❖ What is ARC and difference between weak and unowned ?


ARC:
● It’s keep tracking of object that we have created and still used by
somebody else.




● If he found that object is no longer used by any one then he will release
that object and memory will be automatically deallocated
● ARC is only apply on reference type like class or Closer not Value type
like Struct, Enum etc.
● ARC work on

❖ Ans: https://www.youtube.com/watch?v=zS4AcyjhKFQ

❖ What do mean @escaping and @nonescaping closures in Swift?


❖ Ans: Closures are self-contained blocks of functionality that can be passed around
and used in your code.
Ref : https://medium.com/@kumarpramod017/what-do-mean-escaping-and-
nonescaping-closures-in-swift-d404d721f39

❖ What is Mutating in Swift?


❖ Struct properties can not be modified within Struct methods so by default
Structs properties can’t be mutated inside its own methods to achieve this we use
Mutating

Example
struct City
var population : In
mutating func changePopulation(new : Int)
population = new

var mycity = City(population : 1000


mycity.changePopulation(newpopulation : 2000
print(mycity.population)

❖ What is Equitable and comparable and Hashvalue?


Ref
https://www.youtube.com/watch?v=5zfhRnketTM -imp
https://useyourloaf.com/blog/swift-equatable-and-comparable/

❖ What is access control?


❖ Access control is a security feature which restrict access of code to various internal
and external programs
Ref: https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html

Name Internal Private FilePrivat Public Ope


e n
Derive Class Y N Y Y Y
}

Extension in Same le Y Y Y Y Y
Extension in Other le Y N N Y Y
Same Module / Framework Y Y Y Y Y
Other Module / Framework N N N Y Y
Can Inherited class in same Module Y Y
Can Inherited class in other Module N N N N Y

Open -
1. Can be accessed from anywhere an app or external framework
2. It’s also allow inherited from it
3. It’s method also allow to override it
//module 1
open class Test(){
open func A(){}
}
//module 2
override func A(){} //success

Public-
1. Can be accessed from anywhere an app or external framework
2. It’s not allowed inherit init() and override init()

//module 1
public class TestB(){
public func B(){}
}
//module 2
override func B(){} //error

Internal -
1. Internal is the default access level.
2. Internal classes and members can be accessed anywhere within the same
module(target)/Framework they are de ned

Private - only within class or extention


// B.swift
class B {
private var name = "First Letter"
}
extension B {
func printName(){
print(name) // you may access it here from swift 4. Swift 3 will throw error.
}

fi
fi

fi

B()
B().name // Error even if accessed from outside the class B{} of B.swift le.

File-private -
1. Only within source le
2. Restricts the use of an entity to its de ning source le

// A.swift
Class A {
fileprivate func someFunction() {
print("I will only be called from inside A.swift file")
}
}

// viewcontroller.swift
override func viewDidLoad() {
super.viewDidLoad()
let obj = A()
obj.someFunction() // error
}

❖ Public Properties With Private Setters


❖ As I’ve pointed out in more detail in this post, it’s a common scenario that you don’t
want to provide a public getter, but a private setter. This is a basic principle of
encapsulation. By doing this, only the class itself can manipulate that property, but
can still be accessed and read from outside of the class
EX :
Private(set) var name = “name”

❖ What is method swizzling in Objective C and why would you use it?
❖ As I

Ans:(https://spin.atomicobject.com/2014/12/30/method-swizzling-objective-c/)

❖ What is Safe Aria in ios 9.0 and later


❖ A Safe areas help you place your views within the visible portion of the overall
interface.

❖ How to pass a variable as a reference ?


❖ We need to mention that there are two types of variables: reference and value
types. The difference between these two types is that by passing value type, the
variable will create a copy of its data, and the reference type variable will just point
to the original data in the memory.

fi

fi

fi

fi

Ex; using inout keyword

❖ What is “inout” parameter


❖ Ref
● https://www.hackingwithswift.com/sixty/5/10/inout-parameters
● https://youtu.be/deSLFZvC9vw

❖ Difference between Objective-c and Swift


❖ Ref
● https://redwerk.com/blog/10-differences-objective-c-swift
● https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

VVV IMP
Objective-C => NSArray,NSSet and NSDictionary are the reference typ
Swift => Array, Dictionary and Set are value type

Example:
Objective-C
NSMutableArray * rstArr = [[NSMutableArray alloc] initWithObjects:@"1", nil]
NSMutableArray *secondArr = rstArr
//Case
NSLog(@"%@", rstArr); output : [”1”
NSLog(@"%@",secondArr); output : [”1”
//Case
[ rstArr addObject:@"2"
NSLog(@"%@", rstArr)
NSLog(@"%@",secondArr)
print( rstArr) output : [”1”,”2”
print(secondArr) output : [”1”,”2”]

Swift:
var rstArr = [“1“
var secondArr = rstAr
//Case 1
print( rstArr) output : [”1”
print(secondArr) output : [”1”

//Case
rstArr.append(2
print( rstArr) output : [”1”,”2”
print(secondArr) output : [”1”
If you want to use reference type in Swift then we have to user NSArray,NSSet and
NSDictionary in swift which is available

1.Optionals
● which handle the absence of a value.
fi
fi

fi

fi
fi

fi
2

fi
)

fi
fi
fi

fi

● Optionals say either “there is a value, and it equals x” or “there isn’t a value at
all”
2.Type safety
● Once a variable is declared with a particular type, its type is static and cannot
be changed.
● Swift is a type-safe language, which means the language helps you to be clear
about the types of values your code can work with
● Example: If part of your code requires a String, type safety prevents you from
passing it an Int by mistake
3.Tuples
● Tuple to return multiple values from a function as a single compound value.
var person = ("John", "Smith"
var rstName = person.0 // Joh
var lastName = person.1 // Smith

4.Multiline string
var text = """
This is some text "HI"
over multiple lines
"""
O/P = This is some text "HI"
over multiple lines
print(text)

❖ What is Generic function and swap two values using it


❖ Ref
https://docs.swift.org/swift-book/LanguageGuide/Generics.html

❖ What Type Annotations (Example : var welcomeMessage: String )


❖ You can provide a type annotation when you declare a constant or variable, to be
clear about the kind of values the constant or variable can store
❖ This example provides a type annotation for a variable called welcomeMessage, to
indicate that the variable can store String value

❖ Naming Constants and Variables


❖ Constant and variable names can contain almost any character, including Unicode
characters:
● let π = 3.14159
● let 你好 = "你好世界"

● let 🐶 🐮 = "dogcow"

7.Semicolons
● Unlike many other languages, Swift doesn’t require you to write a semicolon (;)
after each statement in your code, although you can do so if you wish.
However, semicolons are required if you want to write multiple separate
statements on a single line:

fi

● let cat = "🐱 "; print(cat)


8.Integers

● Integers are whole numbers with no fractional component, such as 42 and -23.
Integers are either signed (positive, zero, or negative) or unsigned (positive or
zero)
9.Floating-Point Numbers
● Floating-point numbers are numbers with a fractional component, such as
3.14159, 0.1, and -273.15

5.Guard And Defer


Guard
Guard is new conditional statement which can make this code much more
readable. Guard stops program ow if a condition is not met:

Defer
Swift also gives us the defer keyword, which provides a safe and easy way to handle
code which we want executed only when the program leaves the current scope
It’s execute the code end of function and for that we need to declare that rst

17.Diff Web Service and API


Ans:
https://www.quora.com/What-is-the-difference-between-web-services-and-API
https://www.youtube.com/watch?v=PD_HtuOGuic

Definitions from Wikipedia:


API:
An application programming interface (API) is a set of routines, data structures,
object classes and/or protocols provided by libraries and/or operating system services
in order to support the building of applications.

Web Service:
A Web Service is de ned by the W3C as "a software system designed to
support interoperable machine-to-machine interaction over a network" clearly, both are
means of communications.
The difference is that Web Service almost always involves communication over
network and HTTP is the most commonly used protocol. Web service also uses
SOAP, REST, and XML-RPC as a means of communication. While an API can use
any means of communication e.g. DLL les in C/C++, Jar les/ RMI in java, Interrupts
in Linux kernel API etc. 

So, you can say that-

1. Web Service is an API wrapped in HTTP.



2. All Web Services are API but APIs are not Web Services.

3. Web Service might not perform all the operations that an API would perform.

4. A Web Service needs a network while an API doesn't need a network for its operation.





fi

fl
fi

fi

fi

20)difference between get and post method?

Ans: https://www.w3schools.com/tags/ref_httpmethods.asp

The GET Method

GET is used to request data from a specified resource.


the query string (name/value pairs) is sent in the URL of a GET request:

test/demo_form.php?name1=value1&name2=value2

Some other notes on GET requests:


● GET requests can be cached
● GET requests remain in the browser history
● GET requests can be bookmarked
● GET requests should never be used when dealing with sensitive data
● GET requests have length restrictions
● GET requests is only used to request data (not modify)
● When sending data, the GET method adds the data to the URL; and the
length of a URL is limited (maximum URL length is 2048 characters)

The POST Method

POST is used to send data to a server to create/update a resource.


The data sent to the server with POST is stored in the request body of the HTTP request:

POST /test/demo_form.php HTTP/1.1


Host: w3schools.com
name1=value1&name2=value2

POST is one of the most common HTTP methods.


Some other notes on POST requests:
● POST requests are never cached
● POST requests do not remain in the browser history
● POST requests cannot be bookmarked
● POST requests have no restrictions on data length
● POST requests can be used when dealing with sensitive data

Find the issue?


var a :Int = 10
var b : UInt = 10

Var c:Int = a + Int(b)

Ans:
var a :Int = is Sign Integer which can contain +- value (exm. -10 to 10)
var b : UInt = 10 this is Unsigned Integer which can contain only + value ( 0 to n)

So to perform arithmetic operation we need to convert Uint value to Int


var c:Int = a + Int(b)

Certificates
What is certificate ?
It’s tells your Mac or Xcode that you have access (right) to run the app on the device and you
have the right to upload app on the device

What is device ID ?
With this device ID you can run your application on your iPhone/iPad

We can Create two types of Apple account


1.Developer $99
2.Enterprise $299

Developer account
We can create Two types of certificate
A.Development
B.Production

A. Development
--We can create max to max 3 certificate
--It’s use to test app internally

B.Production
--We can create max to max 3 certificate
--It’s use to upload app on app store

Enterprise account
We can create Two types of certificate
A.Development
B.Production

A. Development
--We can create max to max 3 certificate
--It’s use to test app internally

B.Production

--We can create max to max 3 certificate


--It’s use to upload app on app store

Profiles
There are two types of Profile
1.Development
2.Distribution

1.Development
Use this profile for team (internal development purpose)

2.Distribution
It’s use to upload app on app store

5)what is property?what are the attributes of property?


Ans:
● Property is a piece of data and accessible from outside of the class through its object
without inheriting of that class
● When we Import any class it allow us only public Methods and variables etc.
● It’s a piece of data which hold value and having setter and getter methods

Attribute
● Atomic,Nonatomic,Strong and weak and Copy and retain

#What is difference between frame and bounds:


Frame: Return the receivers frame rectangle, which define the position in its superview.
Bounds: Return the receivers bound rectangle, express its location and size.

6)What type of parser available?which parser we have generally used in iOS?


Ans:
● JSONParser – (NSJSONSerialization)
● XMLParser – (NSXMLParser)

iOS SDK provides classes for handling both of them. For managing JSON data, there is
the NSJSONSerialization class. This one allows to easily convert a JSON data into a
Foundation object (NSArray, NSDictionary), and vise versa.
For parsing XML data, iOS offers the NSXMLParser class, which takes charge of
doing all the hard work, and through some useful delegate methods gives us the tools we need
for handling each step of the parsing.

https://www.appcoda.com/parse-xml-and-json-web-service/

7)what is rest and soap api?


Ans:
API (Application Programming Interface)

SOAP (Simple Object Access Protocol)


● SOAP return data in XML format only
● SOAP used high bandwidth
● SOAP strictly follow it rules (Protocols)
● SOAP use HTTP and SMTP protocol

REST (Representational State Transfer)


● REST return data in text,image,XML and JSON format
● REST used low bandwidth
● REST strictly not follow its rules (Protocol)
● REST use HTTP protocol

SOAP defines its own security whereas REST inherits security from underlying transport.
SOAP does not support error handling but RESThas built-in error handling. REST
is lightweight and does not require XML parsing
SOAP will return XML based data
REST can return XML, plain text, JSON, HTML etc

10)What is the payload size of notification in iOS 8 and iOS


9?
Ans: The maximum size of the payload depends on the notification you are sending:
● For regular remote notifications, the maximum size is 4KB (4096 bytes)
● For Voice over Internet Protocol (VoIP) notifications, the maximum size is 5KB (5120 bytes)

12)what is fast enumeration?


Ans:
● Fast enumeration is an Objective-C's feature that helps in enumerating through a
collection

13)what is the difference between NSSet ,dictionary and


array?
Ans:

NSArray
● NSArray store object in sorted order

NSSet

● NSSet store object not in sorted order


● Come back in any random order

NSDictionary
● It stores objects as key value pairs.
● Objects are not ordered, but can be retrieved simply by addressing them with an
arbitrary string value.

15) Singleton class in iOS?


Ans:
● Singleton classes are an important concept to understand because they exhibit an
extremely useful design pattern. This idea is used throughout the iPhone SDK, for
example, UIApplication has a method called sharedApplication which when called
from anywhere will return the UIApplication instance which relates to the currently
running application
● The Singletons pattern provide a globally accessible, shared
instance of an object.
● https://medium.com/if-let-swift-programming/the-swift-
singleton-pattern-442124479b19

class Calculator {
private init() { }
static let shared = Calculator()
func addition(num1:Int,num2:Int)->Int {
print("Parent")
return num1 + num2
}
}

print( Calculator.shared.addition(num1: 10, num2: 10)


16) IOS architecture?
● COCOA Touch (viewControllers and Storyboards)
● Media (Core Animation Audio & video management)
● Core Services (In-App Purchase , GCD, Foundation framework,iCloud)
● Core OS (Networking, Memory Allocation)

17)App life cycle Delegates ?


Ans:
didFinishLaunchingWithOptions
!
(Active)"##$%&"'%()**+%+,-&(.-/&'%0-11111

!
(In Active) application willResignActive
!
(Background) application didEnterBackground
!
(In Active) "##$%&"'%()*2%$$3)'-45(4-64(7)+8888
!
(Not Running) application willTerminate

18) view life cycle?


Ans:
viewDidLoad
!
ViewWillAppear
!
ViewDidAppear
!
ViewWillDisappear
!
viewDidDisappear

18.)App life cycle State

Not running:

Your app is in this state before it starts up.


The app has not been launched or was running but was terminated by the system

Inactive:
The app is running in the foreground but is currently not receiving events. (It may be executing other code
though.) An app usually stays in this state only briefly as it transitions to a different state

The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.

When your app is running but something happens to interrupt it, like a phone call, it becomes
inactive. Inactive means that the app is still running in the foreground but it’s not receiving events.

Active:

Once your app is started, receiving events.

Backgrounded:
The app is in the background and executing code. Most apps enter this state briefly on their way to being
suspended. However, an app that requests extra execution time may remain in this state for a period of time. In
addition, an app being launched directly into the background enters this state instead of the inactive state. For
information about how to execute code while in the background, see Background Execution.

In this state, your app is not in the foreground anymore but it is still able to run code.

Suspended:

The app is in the background but is not executing code. The system moves apps to this state automatically and
does not notify them before doing so. While suspended, an app remains in memory but does not execute any code.

When a low-memory condition occurs, the system may purge suspended apps without notice to make more space
for the foreground app.

19)Push notification?
Ans:

20)what is layer?
Ans:
● CALayers are simply classes representing a rectangle on the screen with visual content.
● Layers are a lower-level, complex version of the UIView. In reality, it's the UIView
which is a thin layer on top of CALayer
● The size and position of the layer
● The layer’s background color
● The contents of the layer (an image, or something drawn with (CoreGraphics)
● Whether the corners of the layers should be rounded
● Settings for applying a drop shadow to the layer
● Applying a stroke around the edges of the layer

21)what is category(Objective-C) or extension (Swift)?

Protocol Extension
Difference between Category/Extension and Inheritance

Category or extention
1. We can add additional functionality in Class without creating Subclass
2. We can not create store property
3. We can create computed property

Inheritance
We can create store and computed property

23) what is local notification?


Ans:

24)which is more secure core data or user defaults?

Ans:
● User default

25) what is the limit of user defaults?


Ans: As long as there's enough space on the iPhone/iPad, you can store NSUserDefault values.
All those values is stored into a .plist file, and this file is very small, most of the time under 1
kb (unless you store a lot of data).

https://stackoverflow.com/questions/7510123/is-there-any-limit-in-storing-values-in-
nsuserdefaults

26) Current version of Obj C and Main method has 2 arguments arc & argv, what are
those?
Ans: Current version of Obj C 2.0

29)what is posing?
- Objective c allows calss replace fully with another class, that another class is called
“pose as”
https://www.tutorialspoint.com/objective_c/objective_c_posing.htm

31)can objective c support to multiple inheritance?


Ans :No

32)what is sandboxing in iOS?


For security reasons, iOS places each app (including its preferences and data) in a
sandbox at install time. A sandbox is a set of fine-grained controls that limit the app’s
access to files, preferences, network resources, hardware, and so on. As part of the
sandboxing process, the system installs each app in its own sandbox directory, which acts
as the home for the app and its data.

33)What are primitive and non-primitive data types?


Answer :
Primitive data types: boolean, char, byte, short, int, long, float and double.
Non-primitive data types: Classes, Interfaces, and Arrays.

Primitive data types are predefined types of data, which are supported by the programming
language. For example, integer, character, and string are all primitive data types
Non-primitive data types are not defined by the programming language, but are instead
created by the programmer. They are sometimes called "reference variables," or "object
references," since they reference a memory location, which stores the data

The primitive data types include byte, int, long, short, float, double, and char. They are part of
the core of Java and you don't need anything special to use them. For example, the following
declares a long variable for a partNumber

34) What is thread safe ?


Immutable objects are generally thread-safe; once you create them, you can safely pass
these objects to and from threads. ... Mutable objects are generally not thread-safe. To use
mutable objects in a threaded application, the application must synchronize access to them
using locks.

Or
Piece of code is thread safe, if its giving proper output even if working with different
thread. Ex : value type are thread safe.

https://stackoverflow.com/questions/28005734/making-a-class-thread-safe-in-ios

@Objc
A function/variable declared as @objc is accessible from Objective-C, but Swift will
continue to access it directly via static or virtual dispatch. This means if the function/
variable is swizzled via the Objective-C framework, like what happens when using Key-
Value Observing or the various Objective-C APIs to modify classes, calling the method
from Swift and Objective-C will produce different results.

Dynamic Keyword:
Using dynamic tells Swift to always refer to Objective-C dynamic dispatch. This is required
for things like Key-Value Observing to work correctly. When the Swift function is called, it
refers to the Objective-C runtime to dynamically dispatch the call.

37) What is PEM file ?


(Privacy Enhanced Mail / Product Error Message)
https://www.simicart.com/blog/create-pem-file-ios-push-notifications-part-1/

39) UITableView: Automatic Row Height


http://www.thomashanning.com/uitableview-automatic-row-height/

//tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)


tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
tableView.reloadData()

40. What is “dispatch_once”


(Ans : Executes a block object once and only once for the lifetime of an application.)

Example Obj-C =

+ (WebServiceHelper *)sharedInstance
{
static WebServiceHelper *shared = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
shared = [WebServiceHelper new];
});
shared.BaseUrl= BaseUrl;
shared.loadingText = @"Loading";
return shared;}

URLSession In Swift:
URLSession:

The URLSession class and related classes provide an API for downloading data from and
uploading data to endpoints indicated by URLs. The API also enables your app to perform
background downloads when your app isn’t running or, in iOS, while your app is
suspended. A rich set of delegate methods support authentication and allow your app to
be noti ied of events like redirection.

URLCon iguration:
An URLSessionConfiguration object de ines the behavior and policies to use when
uploading and downloading data using an URLSession object. When uploading or
downloading data, creating a con iguration object is always the irst step you must take.
You use this object to con igure the timeout values, caching policies, connection
requirements, and other types of information that you intend to use with
your URLSession object.

URLRequest:
URL request is used to define information related to request which includes http methods, http
body and other fileds.

Di erence between NSURLSession and NSURLConnection

NSURLSession

NOTE : (NSURLConneciton is Deprecated in OS X 10.11 and iOS 9.0)

1) NSURLSession is designed around the assumption that you’ll have a lot of


requests that need similar con guration (standard sets of headers, etc.), and makes
life much easier.

2) NSURLSession also provides support for background downloads,which make it


possible to continue downloading resources while your app is not running or when it
is in the background on iOS.

3) NSURLSession also provides grouping of related requests,Making is easy to


cancel all of the requests associated with a particular work unit, such as canceling all
ff

f
f

fi

f
of the requests associated with a particular work unit,such as canceling all loads
associated with loading a web page when the user closes the window or tab

4) NSURLSession also provides nicer interfaces for requesting data using blocks,n
that it allows you to combine them with delegate methods for doing custom
authentication handling, redirect handling, etc.

NSURLSessionCon guration Types

1) defaultSessionCon guration

The default session con iguration uses a persistent disk-based cache (except when the
result is downloaded to a ile) and stores credentials in the user’s keychain. It also stores
cookies (by default) in the same shared cookie store as
the NSURLConnectionand NSURLDownload classes.

2) ephemeralSessionCon guration

An ephemeral session con iguration object is similar to a default session con iguration
(see default), except that the corresponding session object doesn’t store caches, credential
stores, or any session-related data to disk. Instead, session-related data is stored in RAM.
The only time an ephemeral session writes data to disk is when you tell it to write the
contents of a URL to a ile.
3) backgroundSessionCon guration

Lets the session perform upload or download tasks in the background. Transfers
continue even when the app itself is suspended or terminated.

Types of NSURLSessionTasks

1) Data tasks (NSURLSessionDataTask)

Data tasks are used for requesting data from a server, such as JSON data. These
data are usually stored in memory and never touches the File System We can use
NSURLSessionDataTask.

Syntax and params:

let session = URLSession(configuration: configuration)


session.dataTask(with request: URLRequest, completionHandler: @escaping
(Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
}

2) Upload Tasks (NSURLSessionUploadTask)

Upload tasks are used to upload data to a remote destination. We can use
NSURLSessionUploadTask.

3)Download Tasks (NSURLSessionDownloadTask)

Downloading a le and Storing in a temporary location. We can use


NSURLSessionDownloadTask.

Main di erence between NSURLSession and NSURLConnection

NSURLConnection:

ff
fi
fi
f
f
fi
f

f
fi
fi

f
if we have an open connection with NSURLConnection and the system interrupt our
App, when our App goes to background mode, everything we have received or sent
were lost.

NSURLSession

solve this problem and also give us out of process downloads. It manage the
connection process even when we don’t have access. You will need to use

  application:handleEventsForBackgroundURLSession:completionHandler in your
AppDelegate

1.UITabbarviewcontroller

•A container view controller that manages a radio-style selection interface,


where the selection determines which child view controller to display.

• Each tab of a tab bar controller interface is associated with a custom view
controller. When the user selects a speci c tab, the tab bar controller
displays the root view of the corresponding view controller, replacing any
previous views. (User taps always display the root view of the tab, regardless
of which tab was previously selected. This is true even if the tab was already
selected.)

• class UITabBarController : UIViewController

1.Navigation controller

•A navigation controller is a container view controller that manages one or more


child view controllers in a navigation interface. In this type of interface, only
one child view controller is visible at a time. Selecting an item in the view
controller pushes a new view controller onscreen using an animation,
thereby hiding the previous view controller. Tapping the back button in the
navigation bar at the top of the interface removes the top view controller,
thereby revealing the view controller underneath.

• class UINavigationController : UIViewController

Syntax: let navVC : UINavigationController =


UINavigationController(rootViewController: conterollerVC)

1.UITableview

•A table view displays a list of items in a single column.

• UITableView is a subclass of UIScrollView, which allows users to scroll through


the table, although UITableView allows vertical scrolling only. 

• The cells comprising the individual items of the table


are UITableViewCell objects; UITableView uses these objects to draw the
visible rows of the table. Cells have content—titles and images—and can
have, near the right edge, accessory views

fi
• Table views can have one of two
styles, UITableView.Style.plain and UITableView.Style.grouped. 

syntax : init(frame: CGREct(), Style:plain)

1.Collectionview

• Collection view display the list of items in multiple column and also allow to
scroll items vertical and horizontal also.

• An item is the smallest unit of data you want to present. For example, in a
photos app, an item might be a single image. The collection view presents
items onscreen using a cell, which is an instance of
the UICollectionViewCell class that your data source con gures and
provides.

• class UICollectionView : UIScrollView

• in addition to its cells, a collection view can present data using other types of
views too. These supplementary views can be things like section headers
and footers that are separate from the individual cells but still convey some
sort of information. Support for supplementary views is optional and de ned
by the collection view’s layout object, which is also responsible for de ning
the placement of those views.

Stack view
Stack views provide an easy way to lay out a series of views horizontally or vertically.
1. Horizontal stack view. 2. Vertical Stack view.

The stack view manages the layout of all the views in its arranged Subviews property
Overview. Stack views let you leverage the power of Auto Layout, creating user
interfaces that can dynamically adapt to the device's orientation, screen size, and any
changes in the available space
This is for iOS 9 and above feature ( https://www.appcoda.com/stack-views-intro/

Autolayout
Auto layout is a constraint-based layout system. It allows developers to create an
adaptive UI that responds appropriately to changes in screen size and device
orientation.

IMP LINK
#MVVM – In deep
https://medium.com/swift-india/mvvm-1-a-general-discussion-764581a2d5d9

fi
fi

fi

MVVM bene ts and rules


h ps://cocoacasts.com/what-are-the-bene ts-of-model-view-viewmodel
#MVVM With KVO data binding
h ps://medium.com/@al anlosari/simple-ios-mvvm-with-cocoa-key-value-observer-
f1494e730009
#Login example in MVVM
h ps://www.iosapptemplates.com/blog/ios-development/mvvm-swi

GIT and SVN


https://www.edureka.co/blog/interview-questions/git-interview-questions/

#Sta c dynamic framework


h ps://www.vadimbulavin.com/sta c-dynamic-frameworks-and-libraries/

#Create Framework with Carthage


h ps://samwize.com/2018/06/27/crea ng-a-private-framework-with-carthage/

#Inheritance Advanstages and disadvantages


h ps://prac ce.geeksforgeezks.org/problems/what-are-advantages-and-disadvantages-of-
using-inheritance

#is-a and has-a oops


h ps://www.w3resource.com/java-tutorial/inheritance-composi on-rela onship.php

#Prototype in sswi
https://theswiftdev.com/swift-prototype-design-pattern/

#coredata
h ps://developer.apple.com/documenta on/coredata/se ng_up_a_core_data_stack -
Se ng up core data
h ps://www.raywenderlich.com/7569-ge ng-started-with-core-data-tutorial - Sample app
and key points + integra on
h ps://medium.com/@chetan15aga/ios-interview-ques ons-part-5-core-data-dc97e29835f8

#cocoapods vs caertage
h ps://www.codementor.io/blog/swi -package-manager-5f85eqvygj

#protocol oriented language


h ps://www.appcoda.com/protocols-in-swi / - in deep
h ps://medium.com/ios-os-x-development/how-protocol-oriented-programming-in-swi -
saved-my-day-75737a6af022

#RestAPI and networking


h ps://ma eomanferdini.com/network-requests-rest-apis-ios-swi /

#Swi 4 feature and cadable


h ps://www.hackingwithswi .com/swi 4

#Swi 5 Feature
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tti
ti
ft
ft

tt
ti
fi

ti

fi

ft

ti

ft
ti
ft
ti
tti

fi
ft

ti
tti
ti
ft

ti

ft

#Swi 5.3 Fetaures


h ps://www.youtube.com/watch?v=iJiGjrxVSS4

Security:
h ps://www.netguru.co/blog/ios-app-security-how-to-protect-users-sensi ve-data-in-mobile-
applica ons\

#SSL Pinning :
h ps://appinven v.com/blog/ssl-pinning-in-ios-app/

Codable :
h ps://hackernoon.com/everything-about-codable-in-swi -4-97d0e18a2999
h ps://learnappmaking.com/codable-json-swi -how-to/

#Factory Method
• Class factory methods are implemented by a class as a convenience for clients. They
combine alloca on and ini aliza on in one step and return the created object.

#Guard let , var , etc


h ps://medium.com/@abhimuralidharan/if-let-if-var-guard-let-and-defer-statements-in-
swi -4f87fe857eb6

#Map
h ps://medium.com/@abhimuralidharan/higher-order-func ons-in-swi - lter-map-reduce-
atmap-1837646a63e8

#Closures in swi
h ps://docs.swi .org/swi -book/LanguageGuide/Closures.html
h ps://medium.com/the-andela-way/closures-in-swi -8aef8abc9474

#KVO deep - how is know no fy


h ps://nalexn.github.io/kvo-guide-for-key-value-observing/

Block:
h ps://stackover ow.com/ques ons/39609727/di erence-between-comple on-handler-
and-blocks-ios
h ps://www.appcoda.com/objec ve-c-blocks-tutorial/

#Memory leake(detect and resolve)


h ps://medium.com/ awless-app-stories/memory-leaks-in-swi -bfd5f95f3a74

GCD:
h ps://www.appcoda.com/grand-central-dispatch/

Design pa erns:
h ps://www.raywenderlich.com/477-design-pa erns-on-ios-using-swi -part-1-2

# Di between WKWebview and UIWebview


fl
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
ft
ff
ft

ti

tt

ti
ft
ft

ti

fl

fl

ft
ti
ti

ti
ti
ti

ft
tt

ff

ft

ft

ti

ft
ft

ft
fi
ti

ti

h p:// ndnerd.com/list/view/Major-Feature-Di erence-Between-UIWebView-and-


WKWebView/34217/

#Tuples
h ps://www.tutorialspoint.com/swi /swi _tuples.htm

1. Cocoa and cocoa touch


h ps://stackover ow.com/ques ons/2297841/cocoa-versus-cocoa-touch-what-is-the-
di erence

2. Class hierarcgy NSObject


h ps://stackover ow.com/ques ons/3323209/class-hierarchy-of-nsobject

# UI Development Basics
#Mul plier
h ps://www.youtube.com/watch?v=d4UOV0QPVUI
#Auto layout, Size class and vary for trait
h ps://www.youtube.com/watch?v=k 9xJRuVEk
#UICollec onview Flow layout
h ps://www.youtube.com/watch?v=6HiX8SlEKnc
#How to add delete swap bu on to tableview
h ps://www.hackingwithswi .com/example-code/uikit/how-to-customize-swipe-edit-
bu ons-in-a-uitableview
#UI related Interview Ques ons
h ps://medium.com/@chetan15aga/ios-interview-ques ons-part-4-uikit-a8b6c8fda042

#Architectures basics
h ps://mindster.com/ios-app-architecture-best-prac ces/
h ps://yellow.systems/blog/guide-to-the-chat-architecture
h ps://hackernoon.com/how-to-build-an-ecommerce-app-feeea1c10808

Op onal:
#react na ve - Interview ques on
h ps://www.fullstack.cafe/blog/react-na ve-interview-ques ons
h ps://github.com/sudheerj/reactjs-interview-ques ons#what-is-react
h ps://www.netguru.com/codestories/react-na ve-component-lifecycle
h ps://blog.logrocket.com/naviga ng-react-na ve-apps-using-react-naviga on/
h ps://enappd.com/blog/how-to-make-api-calls-in-react-na ve-apps/125/

Firebase No ca on
h ps://www.iosapptemplates.com/blog/ios-development/push-no ca ons- rebase-swi -5

MACOS:
h ps://www.raywenderlich.com/731-macos-development-for-beginners-part-1

//Facebook post
h ps://developers.facebook.com/docs/sharing/ios/

#How release the app


tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
tt
ff
tt
ti
ti
fi

ti
ti

ti
fi
ti

fl
fl

ti

tt
ft
ti

ti
ti

ti
ft
fl

ti
ft

ti
ff
ti

ti

ti

ti

ti
ti

ti
fi

ti

ti

fi

ft

h ps://instabug.com/blog/how-to-submit-app-to-app-store/
h ps://medium.com/@the_manifest/how-to-publish-your-app-on-apples-app-store-in-2018-
f76f22a5c33a
#what is appgroup:
h p://www.theappguruz.com/blog/ios8-app-groups

#Google Maps:
h ps://stackover ow.com/ques ons/20905797/google-maps-ios-sdk-ge ng-direc ons-
between-2-loca ons

#Realm database
https://dzone.com/articles/how-realm-is-better-as-compared-to-sqlite in details
h ps://realm.io/docs/swi /latest/ imp to understand realm opera ons
h ps://www.appcoda.com/realm-database-swi / - details all
What is Realm database? In simple terms, Realm is a non-relational
database management system which allows you to declare relationships
between objects the same as you would do in any object graph in your
language of choice. Realm is mostly used for mobile app development.

# How to set primary key in realm table:


primaryKey needs to be a class function which returns the name of the property which is
the primary key, not an instance method which returns the value of the primary key.

class Foo: RLMObject {


dynamic var id = 0
dynamic var title = ""

override class func primaryKey() -> String? {


return "id"
}
}

Set 9:
Delegate protocol - No ca on
KVO deep - how is know no fy
Closure - (Di between block and closure)
MVC and MVVM
What will use when you give build to user to handle crash - crashes analy cs etc or other ways
What r u using to delivery build - gen ans , circle CI
Google map handling.
Unit test cases.
Objec ve c and swi di erences - as per developer
tt
tt
tt
tt
tt
tt

ti
ff

ti

fl

ft

ti
ff
fi
ft

ti
ti

ti
ti

ft

ti

tti
ti

ti

How we add separate network layer in MVVM.


What u use on objec ve
Alamo re what used in background - NSURLSession
is Alamo re support for objec ve c4321 - no objc c support AFNetworkking or NSURLSession

Third party process -


CICD -
Test coverage - Thought Xcode Test.
Unit test - In deep

Swi version started from .3


How to handle concurrency. —GCD and Opera on Queues
Closure
Design pa erns
Architecture- MVC, MVVM and VIPER
Third party integra on - Cocoapods Carthage

How you follows GIT process.

Architecture for app like amazon there is di erent modules like payment etc.
• Analysis the requirement of the applica on and features.
• Will decide architecture asper project complexity for modulraty , testability and
reusability
There will be products list where user can order and manage their items.
Also there is accoun ng modules for payment and invoice for order.
⁃ If there are mul ple modules

• How to make tableview cell with mul ple controller lets say 10 and some me show 5
or 8 etc how will you do?
• When you do load more how to reload table with reloaddata or else, if reload data
then it will be very s cky.
• What is layout and layout if needed?
• What happened if controller dismissed then can couture retain cycle breaks or not.

Set 10:
⁃ Access speci ers in swi . Di erence between open & public && private le private.
⁃ Cocoapods and carthage di erence.
⁃ Di rence In pod update vs pod install.
⁃ Lazy in swi di erent cases.
⁃ Objec ve C vs Swi .
⁃ How to communicate to view to viewmodel – ex delegate/protocol/no ca on
observer/closures.
⁃ UIWebview vs WKWebview

⁃ What is abstract class and can we provide body in abstract method in abstract class.
ff
ft
ti
fi

fi
tt

ft
fi

ff
ti

ft

ti
ti
ti

ti

ft

ff

ff

ti

ti

ti
ff

ti

ti
fi
fi
ti

ti

⁃ A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods(methods without body) as well as concrete methods (regular
methods with body). A normal class(non-abstract class) cannot have abstract
methods.

2. $$test$30 is string and wanted to remove rst two $ char.


3. How to know generic func on passed object type like string etc
4. What is interface.
⁃ h ps://www.javatpoint.com/interface-in-java
5. What is re ec on
⁃ h ps://www.hackingwithswi .com/example-code/language/how-to-use-re ec on-to-
inspect-type-data

OOPS:
abstrac on and interface di erence
Mul ple inheritance
Sta c and nal sta c
Are we able to do mul ple inheritance with two abreac on classes

Programs:

Array Manipulation:

//Find min number and second min from array


let numbers = [711, 15, 66, 8, 19, 77, -10]

print("Standrad Min \(numbers.min())")


print("Standrad Max \(numbers.max())")

var min = Int.max


var seccondMin = Int.max

for number in numbers {


if number < min {
seccondMin = min
min = number
}
else if number < seccondMin && seccondMin != min {
seccondMin = number
}
}

print("Min Number=> \(min)")


print("Second Min Number=> \(seccondMin)")
tt
tt

ti
ti

ti

fl
fi
ti

ti

ti

ti
ff

ft

fi

ti

fl
ti

//Find max number and second max from array


var max = Int.min
var seccondMax = Int.min

for number in numbers {


if number > max {
seccondMax = max
max = number
}
else if number > seccondMax && seccondMax != max {
seccondMax = number
}
}

print("Max Number=> \(max)")


print("Seccond Max Number=> \(seccondMax)")

String Manipulation:

//*****************************************
//Reverse String
//*****************************************
var str = "Hello, playground"

var revStr = ""


for char in str {
revStr = char.description + revStr
}

print("Standrad reverse=> " + revStr)


print("Without Standrad reverse=> " + String(str.reversed()))

Logical program ex class:


import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {


super.viewDidLoad()
factorialNumber()
fibbonacciSeries()
primeNumber()
reverseString()
palindromString()
largestOrSecondLargestElement()

let arra = [2, 3, 5, 7, 10]


var index = 0
printElementWitoutLoop(arra, index: &index)

printArrayWithStandard()
}

//MARK: - Factorial number, Fibbonacci series, Prime Number


private func factorialNumber() {
//Input 5 => Output 120
let number : Int = 5
var fact = 1
for i in 1...number {
fact = fact * i
}

print("Fact of 5 is \(fact)")
}

private func fibbonacciSeries() {


//Output 0 1 1 2 3 5 8 ...
var x = -1 ,y = 1, sum = 0;
var seriesArr: [Int] = []

for _ in 0..<10 {
sum = x+y;
x = y;
y = sum;

seriesArr.append(sum)
}
print("Fibbonacci series \(seriesArr)");
}

private func primeNumber() {


//1 2 3 5 7 11
var numbers: [Int] = [1]
var flag = 1
for i in 2...20 {
for j in 2..<i {
if i % j == 0 {
flag = 0
break
}
}

if flag == 1 {
numbers.append(i)
}
else {
flag = 1
}
}

print("Prime Numbers: \(numbers)")


}

//MARK: - String Manupulations


private func reverseString() {
let stringToReverse: String = "chetan girase"
print("Reverse String \(String(stringToReverse.reversed()))")
//Using Standrad function

//Reverse string using non standard function


var reverseString = ""
for char in stringToReverse {
reverseString = char.description + reverseString
}
print("Reverse String using non function => \
(reverseString)")
}

private func palindromString() {


let palString = "MOM"
var endIndex = palString.count-1
var flag = true

for i in 0...endIndex {
if palString[i] != palString[endIndex] {
flag = false
break
}
endIndex = endIndex - 1
}

if flag {
print("String is palindrom")
}
else {
print("String is not palindrom")
}
}

private func largestOrSecondLargestElement() {

let numbers = [711, 15, 66, 8, 19, 77, -10]

print("Standrad Min \(numbers.min())")


print("Standrad Max \(numbers.max())")

var min = Int.max


var seccondMin = Int.max

for number in numbers {


if number < min {

seccondMin = min
min = number
}
else if number < seccondMin && number != min {
seccondMin = number
}
}

print("Min Number=> \(min)")


print("Second Min Number=> \(seccondMin)")

//MARK: - Array Manupulations


private func printElementWitoutLoop<T>(_ array: [T], index: inout
Int) {
guard !array.isEmpty && index < array.count else {
return
}

print(array[index])
index += 1
printElementWitoutLoop(array, index: &index)
}

private func printArrayWithStandard() {


let arra = ["2", "2", "5", "7", "2"]
dump(arra)
let joinedStrings = arra.joined(separator:"/n")
print("joinedStrings: \(joinedStrings)")

let occureanceCount = arra.filter({ $0 == "2" }).count


print("Occurence Count \(occureanceCount)")
}
}

extension StringProtocol {
subscript(offset: Int) -> Character {
self[index(startIndex, offsetBy: offset)]
}
}

Program to print:

*
*$*
*$*$*
*$*$*$*

column = 7
rows = 4
counter = 1

for i=0; i<rows; i++ {


for j=1; j<=counter; j++ {
if j%2 == 0 {
print(“$”)
}
else {
print(*)
}
}

print(“/n”)
counter += 2
}













You might also like