0% found this document useful (0 votes)
6 views41 pages

Main Interview Questions

The document outlines key interview questions and answers related to Swift programming, covering topics such as the latest versions of Xcode, macOS, and iOS, differences between Objective-C and Swift, and various Swift features like optionals, tuples, and error handling. It also includes links to external resources for deeper understanding and examples of Swift syntax. Additionally, it discusses advanced concepts like higher-order functions and the singleton pattern.

Uploaded by

mohit20612
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views41 pages

Main Interview Questions

The document outlines key interview questions and answers related to Swift programming, covering topics such as the latest versions of Xcode, macOS, and iOS, differences between Objective-C and Swift, and various Swift features like optionals, tuples, and error handling. It also includes links to external resources for deeper understanding and examples of Swift syntax. Additionally, it discusses advanced concepts like higher-order functions and the singleton pattern.

Uploaded by

mohit20612
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Main Interview Questions

[Link]

1) Correct way of writing os


iOS, macOS, watchOS, and tvOS

2) Latest version of Xcode, macOS and iOS


Xcode: 15.2 included swift 5.9
macOS: Sonorma (14) ← Ventura(13) ← Monterey (12)
iOS version: 17
Swift version : 5.9

3) What’s new in Xcode 15?


[Link]
[Link]

4)What’s new in swift 5.9?


[Link]

5)Column Breakpoints:
[Link]
[Link]

6)What’s new in iOS 17?


[Link]

7) Objective c vs Swift:

[Link]
for-your-next-ios-mobile-app
[Link]

NOTE: In objective c everything was reference type but in swift value type is
also there.

Swift introduces advanced types not found in Objective-C, such as tuples.


Tuples enable you to create and pass around groupings of values. You can use
a tuple to return multiple values from a function as a single compound value.

Swift also introduces optional types, which handle the absence of a value.
Optionals say either “there is a value, and it equals x” or “there isn’t a value at
all”. Using optionals is similar to using nil with pointers in Objective-C, but they
work for any type, not just classes. Not only are optionals safer and more
expressive than nil pointers in Objective-C, they’re at the heart of many of
Swift’s most powerful features

Objective c uses yes no whereas swift uses true , false

Swift also provides range operators that aren’t found in C, such


as a..<b and a...b, as a shortcut for expressing a range of values.

8) What is OS Log
[Link]

9) Cocoa vs Cocoa Touch


[Link]
what-is-the-difference

10) Declare multiple constants or multiple variables on a single line


var x = 0.0, y = 0.0, z = 0.0
var red, green, blue: Double

var a, b, c: Double
var a: Double, b: Double, c: Double

var a, b: Int, c, d: Double


var a: Int, b: Int, c: Double, d: Double

11) What is ternary condition


The ternary operator is a shorthand way to write a basic if-else statement
Syntax:
condition ? valueIfTrue : valueIfFalse

12) Type Annotations

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. Write a
type annotation by placing a colon after the constant or variable name, followed
by a space, followed by the name of the type to use.
This example provides a type annotation for a variable called welcomeMessage,
to indicate that the variable can store String values:

var welcomeMessage: String

13) What is collection types in swift


Array set dictionary

14) Type Safe


If part of your code requires a String, you can’t pass it an Int by mistake.

Var age = 10
age = “hello”. // Compiler will return error

15) How to use reserve keyword in swift as a variable or constant


We can use backticks (`)

eg:
let`class` = 10

16) What are the param of print function


print(items: Any, separator: String, terminator: String )

print("Okay","Great",separator: "Seprator",terminator: "ternimator")

Output : OkaySepratorGreatternimator

. What are integers?


Integers are whole numbers with no fractional component such as 42 and -23

18)Unsigned vs signed int


Integers are either signed (positive, zero, or negative) or unsigned (positive or
zero).

19)What is floating-point number


Floating-point numbers are fractional numbers such as 3.14159, 0.1

20)Float vs Double in swift


● Double represents a 64-bit floating-point number.
● Float represents a 32-bit floating-point number.
Double has a precision of at least 15 decimal digits, whereas the precision
of Float can be as little as 6 decimal digits

Note: When you declare a variable with floating value swift always consider it
as double. In order to declare float
you need to use type annotation as Float

let myDouble: Float = 1.234567890


Output : 1.234568

let myDouble: Double = 1.2345678901234567


Output: 1.234567890123457

21)Type inference

Compiler will automatically decocts the data type based on value assign

● let meaningOfLife = 42
● // meaningOfLife is inferred to be of type Int

22)Type aliases

Type aliases define an alternative name for an existing type. You define type
aliases with the typealias keyword.
Type aliases are useful when you want to refer to an existing type by a name
that’s contextually more appropriate, such as when working with data of a
specific size from an external source:

typealias AudioSample = Int

23) How to get random value of bool variable


let boolValue = [Link]()

24) How to toggle the value of boolean


Using toggle() function

25)Tuple
[Link]
tuples#:~:text=In%20Swift%2C%20a%20tuple%20is,be%20of%20different%2
0data%20types

Note: The tuple index always starts with 0. Hence, the first element of a tuple is
present at index 0, not 1.

26) What is named Tuple ?


Named tuple means accusing tuple using properties not 0 or 1
eg: var userInfo: (name: String, age: Int) = ("Aman", 29)

Note: It is the best practice to use the named tuples as it makes our code more
readable.

27) Can we add or remove values inside tuple


No we can’t

28) Nested Tuple


A tuple can have another tuple inside it that is called nested tuple

var laptopLaunch = ("MacBook", 1299, ["Nepal": "10 PM", "England": "10 AM"])
print(laptopLaunch.2) Output : ["Nepal": "10 PM", "England": "10 AM"]
laptopLaunch.2["USA"] = "11 AM"
print(laptopLaunch.2) Output: ["Nepal": "10 PM", "England": "10 AM",
"USA": "11 AM"]

29)What is Tuple Destructuring

Tuple destructuring means pulling a tuple apart into multiple variables with a
single assignment

func getInfo() -> (name: String, email: String) {


return (name: "Matt", email: "matt@[Link]")
}

let (name, email) = getInfo()


print(name) // prints "Matt"
print(email) // prints "matt@[Link]"

30) What is optional in swift?


Optional means value may or may be present

31) What is nil in swift?


You set an optional variable to a valueless state by assigning it the special
value nil:

32)Optional binding vs optional Chaining

32)What is force Unwrapping?

You can access the value by adding an exclamation mark (!) to the end of the
optional’s name. This is known as force unwrapping the optional’s value. App
will crash if value will be nil

let possibleNumber = "123"


let convertedNumber = Int(possibleNumber)
let number = convertedNumber!

32)What is Implicit warp optionals vs Explicit warp

Sometimes it’s clear from a program’s structure that an optional


will always have a value, after that value is first set. In these cases, it’s useful to
remove the need to check and unwrap the optional’s value every time it’s
accessed, because it can be safely assumed to have a value all of the time.
These kinds of optionals are defined as implicitly unwrapped optionals

You write an implicitly unwrapped optional by placing an exclamation point


(String!) rather than a question mark (String?) after the type that you want to
make optional. Rather than placing an exclamation point after the optional’s
name when you use it, you place an exclamation point after the optional’s type
when you declare it.

let possibleString: String? = "An optional string."


let forcedString: String = possibleString! // Requires explicit unwrapping

let assumedString: String! = "An implicitly unwrapped optional string."


let implicitString: String = assumedString // Unwrapped automatically

Note: In implicit unwrap we need to declare optional with ! Symbol and in


explicit unwrapping either we need to use ! Sign or provide default value

33) Error handling in Swift

[Link]
language/errorhandling/

Eg:

enum CustomError: Error {


case left
case right
}

class Test {
func handleError() throws -> Bool {
if 1 == 1 {
throw [Link]
}

do {
let value = try Test().handleError()
print(value)
} catch [Link] {
print("Left")
} catch [Link] {
print("Right")
}

NOTE: error inside is accessible directly if catch statement is not written.


eg

do {
let value = try Test().handleError()
print(value)
} catch {
print(error)
}
34) Assertions and Preconditions
They are used to check the condition. If condition fails app crashes
The difference between assertions and preconditions is in when they’re
checked: Assertions are checked only in debug builds, but preconditions are
checked in both debug and production builds. In production builds, the
condition inside an assertion isn’t evaluated. This means you can use as many
assertions as you want during your development process, without impacting
performance in production.

35) Unary Minus Operator


Toggle the numeric value

let three = 3
let minusThree = -three // minusThree equals -3
let plusThree = -minusThree // plusThree equals 3, or "minus minus three"

36) Unary plus Operator


The unary plus operator (+) simply returns the value it operates on, without any
change:

let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix equals -6

It provide symmetry in code

37)Compound Assignment Operators

+=, -=

38)Can we compare Tuple as well ?


Yes we can

(1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple"
aren't compared
(3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less
than "bird"
(4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to
"dog"

("blue", -1) < ("purple", 1) // OK, evaluates to true


("blue", false) < ("purple", true) // Error because < can't compare Boolean
values
39)Nil-Coalescing Operator
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value,
or returns a default value b if a is nil. The expression a is always of an optional
type. The expression b must match the type that’s stored inside a.
The nil-coalescing operator is shorthand for the code below:
a != nil ? a! : b

Note
If the value of a is non-nil, the value of b isn’t evaluated. This is known as short-
circuit evaluation.

40)What are Range operators

41)Closed Range Operator


The closed range operator (a...b) defines a range that runs from a to b, and
includes the values a and b. The value of a must not be greater than b.

for index in 1...5 {


print("\(index) times 5 is \(index * 5)")
}

42)Half-Open Range Operator


The half-open range operator (a..<b) defines a range that runs from a to b, but
doesn’t include b.

43)One-Sided Ranges
let names = ["Anna", "Alex", "Brian", "Jack"]

for name in names[2...] {


print(name)
}
// Brian
// Jack

for name in names[...2] {


print(name)
}
44)Extended String Delimiters
We can use this if we want to use special characters in string

let sentence = #"They said\n "It's okay", didn't they?"#


print(sentence) Output: They said\n "It's okay", didn't they?

45)Charcters
Character means single character value
Swift alaways consider String over character
If you want to use character then you can use type annotation as character

var sentence:Character = "C"


[Link](“Z”). // this will give compile error

46)What will be the output of below code


let value: Character = "OK"

It will give compile error

47)What will be output of below code

let badStart = """


one
two
"""
let end = """
three
"""

print(badStart + end).

Output:
one
twothree

let badStart = """


one
two

"""
let end = """
three
"""

print(badStart + end)

Output:
one
two
three

48)What is String Interpolation?


String interpolation is a way to construct a new String value from a mix of
constants, variables, literals, and expressions by including their values inside a
string literal. You can use string interpolation in both single-line and multiline
string literals. Each item that you insert into the string literal is wrapped in a
pair of parentheses, prefixed by a backslash (\):
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"

7) For Commenting:

There are Three options to add #pragma_mark in Swift:

// MARK: - your text here -

// TODO: - your text here -

// FIXME: - your text here -

[Link]

What is print

print("first","second",separator: " here ", terminator: "")

8) Print vs debug Print:

[Link]
9) Xcode 13 Features:

[Link]

9) Xcode 14 Features:

[Link]

10) Singleton Pattern:

[Link]

[Link]

Youtube: [Link]
Disadvantage of Singleton: [Link]

11) Higher Order Functions:

[Link]
order-functions/

[Link]
filter-reduce-dff60b5b6adf

[Link]
function-in-swift (Explained in End)

Complexity:
[Link]
Functions-In-
Swift#:~:text=Time%20complexity%3A%20O(m%20%2B,the%20length%20of
%20the%20result.=

Flat map: used to flattened objects into single array or collection of array into
single array
var arrayOfObj = [["1","2"],["3","4"]]
print( [Link]({$0}))
Output : ["1", "2", "3", "4"]

12) Clousers :

Escaping Closures
A closure is said to escape a function when the closure is passed as an
argument to the function, but is called after the function returns. When you
declare a function that takes a closure as one of its parameters, you can write
@escaping before the parameter’s type to indicate that the closure is allowed
to escape.

Youtube: [Link]
[Link]

Auto Clousers:
[Link]
autoclosure-what-why-and-when-swift-641dba585ece

Trailing Clousers:
[Link]
syntax#:~:text=If%20the%20last%20parameter%20to,after%20the%20functio
n%20inside%20braces

Another site link (Easy explained)


[Link]

13) Defer :

[Link]

Youtube: [Link]

14) IBInspectable vs IBdesignable

[Link]

15) IF Debug:
#if DEBUG
#endif

16) Whats new in swift 5.5 :

[Link]
fb13f49bb728
[Link]

16) Whats new in swift 5.7 :


[Link]
[Link]

17) View Controller Life Cycle:

[Link]
cycle-2a0f02e74ff5

18) App Delegate Life Cycle or iOS app Life Cycle:

[Link]

19) FCM VS APNS:

[Link]
Differences-between-FCM-and-APNS

[Link]
[Link]#:~:text=FCM%20is%20sent%20as%20JSON,APNS%20requires%20
their%20proprietary%20platform

20) p12 vs p8:

[Link]
21) App Dot Colours:

[Link]
app-25c571171179

22) KVO vs KVC:


[Link]
dceadfcf1b28#:~:text=KVO%20and%20KVC%20or%20Key,that%20inherits%2
0NSObject%20at%20runtime

22) What is UIApplication


[Link]

23) What happen if I return false in didFinishLaunchingWithOptions?

23) Internal vs External Testing:

[Link]
and-external-testers-in-itunes-testflight-beta-testi

19) Tight vs loose coupling:

[Link]
loose-coupling-and-tight-coupling-in-the-object-o

Eg: [Link]
coupling-and-loose-coupling-in-java

20) Payments:

Razor Pay:
[Link]
standard-sdk/

Paypal:
[Link]
[Link]

In App :
[Link]
applications-swift-4d1649509599

Apple Pay:
[Link]
ios-app-71f17d48fc9b

21) Frame vs Bound:

[Link]
between-the-frame-and-the-bounds

What is the iOS Architecture?

What is retain Cycle?


[Link]
swift-ed4aefedb01a

When would you choose structs and classes and why?


[Link]
structures-and-classes

What is QoS (Quality of Service)

[Link]
Conceptual/EnergyGuide-iOS/[Link]

What is Code Signing in iOS & How it Works?

[Link]
works-a3c4ecfd90bf
Why don’t structs support inheritance?
[Link]
inheritance-2e6e3171e870

What is static dispatching & dynamic dispatching?


[Link]
[Link]

What is profiling?
[Link]
xcode-9df65e1f7277

App Theming in Swift

Cocoa and Cocoa Touch — The difference

[Link]
what-is-the-difference
[Link]
c1289dbffbc3

Thread Sanitizer
[Link]
sanitizer-56a887dc144

22) oops Concept:

[Link]

23)Arc (Weak vs strong and unowed weak):

[Link]
[Link]

[Link]
reference-counting-521d9998be

Youtube : [Link]

24) Optionals:

[Link]

25) Property wrappers:

[Link]

26)Link List:

[Link]

27)Access Specifer:

Open : access outside the framework or defining module


Public : access outside the framework or defining module but can not be
inherited
Internal : access within the framework or defining module
Private: access within the class
File Private: access within the file

Youtube [Link]

28) Code improvement and Solid Principle:

[Link]
review-18cc6f6fb5b3

Youtube : [Link]
[Link]
[Link]
And All suggestion links on YouTube
29) Static Keywords:

[Link]

30)Class vs struct :

[Link]
[Link]

31) App thinning:

[Link]
[Link]

32) Self vs self

[Link]

self is a reference to the current object (“instance”) of a class (or struct), within
that class

33) Scene Delegate vs App delegate

[Link]
delegate-7503d48c5445

34) Layout if needed vs Set display

[Link]
layoutifneeded-vs-layoutsubviews-5a2b486da31c
[Link]
setneedsdisplay

35) GCD and NSoperation Quueue


[Link]
36) Initializers

Youtube
[Link]
[Link]

37) Nill conseling operator

[Link]
coalescing-operator

38) Property observers

[Link]

will set vs did set


var age: Int? {

didSet {
print("Age did Set")
}
willSet {
print("Age will Set")
}

}
In Viewdidload() {
age = 12
age = 40
}

Will set will call before value is stored and did set is called after value is stored.

39) Computed properties:

[Link]

40) Does iOS support multiple inheritance :


No . You can conform any protocol instead

[Link]
41) Software development life cycle:

Planning
An analyse
Design develop
Test
maintain

42) discardableResult

[Link]

43) All Keywords

[Link]
v-3-0-1-f59783bf26c

44) Dependency Injection

Dependency injection means giving an object its instance variables. Really.


That's it.

[Link]
[Link]

Youtube
[Link]
[Link]
[Link]

EG:
protocol MyApiProtocol {
func fetchData()

}
class Utility: MyApiProtocol {
func fetchData() {
print("Fetch the req data")
}

class LoginVC {

var value: MyApiProtocol


init(value:MyApiProtocol) {
[Link] = value
}

func getData() {
[Link]()
}

let obj = LoginVC(value: Utility())

[Link]()

45) Thread Safe:

Thread Unsafe - If any object is allowed to modify by more than one thread at
the same time.

Thread Safe - If any object is not allowed to modify by more than one thread at
the same time.
Eg: from same bank account two persons are withdrawing money one from atm
other from net banking same time.

46) Collection Type :


Array , set and dictionary
47) @objc

private mean it visible only in Swift. so use @objc to visible in Objective-C. If


you have a func to selector a private func in swift, it is required.
The @objc attribute makes your Swift API available in Objective-C and the
Objective-C runtime.

[Link]

48) atomic vs non atomic , assign and copy

[Link]
copy-582b79d31568

[Link]
the-atomic-and-nonatomic-attributes

[Link]
course-d11c23f4366c

49) Missing DSYM

[Link]
files-777b82759683

50) What is category

51) All Swift basics

[Link]

52) Error handling in Swift

[Link]
53)What is generic

[Link]

Youtube: [Link]

54)Operator overloading

[Link]
operator-overloading

55)Super keyword

[Link]

56)Final keyword

[Link]

57)Actor

[Link]

59)Type casting

[Link]

Upper vs down casting


[Link]
64)enum

[Link]
[Link]

65)Sets

[Link]

66)Dictionary

[Link]

67)Array

[Link]

68)Optional binding vs optional Chaining (Duplicate)

[Link]

69)Lazy in swift

70Associated types

Means add generic support in protocols

[Link]
71) Opaque return type

Hiding return type


Eg we can use some keyword

func getData() -> some Collection {

return [1,2,3,4,5]
}

[Link]

72)Hashable

[Link]
sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwjByf
CXzMn1AhVD4jgGHQpsA3AQFnoECAwQAw&url=https%3A%2F%[Link]
m%2F%40paulsoham%2Fhashable-172c10a749b8&usg=AOvVaw3K6TkrGR9n9
cwL1Kc6XW7N

73)Big O notation and complexity:

[Link]

74)Sorting Algos

[Link]

75)Mutating keyword

[Link]
keyword-mean

[Link]

76)Any vs Any object

[Link]

77)Git commands
78)Protocol Oriented programming

[Link]
[Link]

79)Inout keyword

[Link]
#:~:text=Swift%20inout%20parameter%20is%20a,in%20front%20of%20the%
20parameter

80)When we use pod deinit?

[Link]

81)Stack vs heap memory

[Link]
understanding

[Link]
reference-type-in-ios-swift-18cb5145ad7a

82)Architecture and Design pattern in software

[Link]

83)What is Delegate?

any object that should be notified when something interesting has happened.

84)Class Singleton vs Struct singleton

[Link]
85) Array vs NSArray

Array is value type and NSArray is reference type

NS:- next Step

87)Difference between == and ===

[Link]

88)White box testing vs black box testing

White is done by QA and developers and black box testing is done by end users

89)Fat Protocol

methods (in protocols) which we needs to implement forcefully

Solution:
Create optional methods (only work for classes)
Protocol Extension

90)Method Overloading

Method name same but different parm in same class

91)Method Overriding

Method name same same parm ibut one in base class and other in super class

92)Static vs Dynamic Binding


93)In App Sandbox Time
94)Hierarchy of NsButton

[Link]
uibutton-until-nsobject

95)Content hugging vs compression ratio

[Link]
compression-resistance-priorities-476fb5828ef

96)Set needs display


[Link]
setneedsdisplay-in-ios

97)Socket

[Link]
swift

98)Dependency Injection with Storyboard


[Link]
dependency-injection-with-storyboards
[Link]

99)What is ABI Stability


[Link]
swift-5-187556e3c3ae
[Link]
[Link]

What is link list and types


[Link]

Data Structure
[Link]
implementation/?ref=lbp

Binary tree:
[Link]

Binary Search Tree:


[Link]

Heap
[Link]

Graph :

[Link]

Dependency I section
Advantage and disadvantage

Repository patterns

What is UIAppliction

What is responder

Sqlite vs core data

Object oriented vs protocol oriented

git pull vs fetch


[Link]

Firebase Analytics

ABI Stability
Sandbox
Ssl pinning
Genearte custom random no

[Link]

Git hub

Conflicts

Class vs static methods


[Link]
between-static-func-and-class-func-in-swift

New To Add

Test cases

[Link]

var balance: Double = 5000

let lock = NSLock()

struct BankAccount {

func widthrawMoney(amount: Double, type: String) {


[Link]()
if balance > amount {

print("\(type) Starts \(balance)")


[Link](forTimeInterval: [Link](in: 0...5))
balance = balance - amount
print("\(type) Widhrwal successfull and blance remaining is \(balance)")

} else {
debugPrint("insufficient balance \(type)\(balance)")

}
[Link]()

let queue = DispatchQueue(label: "Atm",attributes: .concurrent)

[Link] {
let obj = BankAccount()
[Link](amount: 3000, type: "ATM")
}

[Link] {
let obj = BankAccount()
[Link](amount:3000, type: "Netbanking")
}

Thread
Thread is often referred to as a lightweight process. The process can be split
down into so many threads. For example, in a browser, many tabs can be
viewed as threads. MS Word uses many threads - formatting text from one
thread, processing input from another thread, etc.

100) What is Pod file?


[Link]
[Link]#:~:text=%3CWhat%20is%20a%20Podfile%3F,should%20simply%
20be%20named%20Podfile%20

101) What is Pod Lock file?


[Link]
lock-87df8c744dc6#:~:text=lock-,Podfile.,pod%20install%20or%20pod%20up
date
[Link]

102) Generics vs Any


[Link]
[Link]
and-anyobject-in-swift

103) Is Swift a dynamic or static language?


[Link]
language
[Link]
#:~:text=Swift%20is%20a%20statically%20typed,be%20specified%20at%20c
ompile%20time

104) What is Comparable Protocol in Swift?


[Link]
swift-8cb854e30cf7#:~:text=Comparable%20protocol%20allows%20you%20t
o,an%20implementation%20for%20the%20%3C%20operator

105) What is Private Set in swift?


[Link]
d115c5598242

106) What is Capture list?


[Link]

107) While vs Repeat While


[Link]

[Link]
between-continue-break-fall-through-throw-and-return-i

108)Method vs function
[Link]
a-method-and-a-function-in-
swift#:~:text=The%20short%20answer%20to%20this,every%20function%20is
%20a%20method

Warning and Error


[Link]
v=lvzcJ62JJmU&list=PL8seg1JPkqgHx8DgGsHB4Dh_H_78x8oQE&index=
3

#warning("Refector the code")


#error("Fix code")

Function inside function example


func calculateValue(a:Int) -> Int {
func odd() -> Int {
5
}
func even() -> Int {
2
}

return a % 2 == 0 ? even() : odd()

}
calculateValue(a: 123)

func test() {
var str = "Hello, World!"
let myClosure = { [str] in
print (str)
}
str = "next"
myClosure()

test()

Another Interview questions:

[Link]
a8b6c8fda042#:~:text=Q%3A%20What%20is%20UIButton%20hierarchy,
%2D%3E%20UIResponder%20%2D%3ENSObject

Code playground

Single responsibility

class Handler {

let api: Api?


let parser: Parser?
let database: Database?

init(api: Api, parser: Parser,database: Database ) {


[Link] = api
[Link] = parser
[Link] = database
}

func handle() {
api?.callApi()
parser?.callparser()
database?.callDatabase()

}
}

class Api {

func callApi() {
print("Api called")
}

class Parser {

func callparser() {
print("parser called")
}

}
class Database {

func callDatabase() {
print("Database called")
}

}
let objhandler = Handler(api: Api(), parser: Parser(), database: Database())
[Link]()

LSKV

import UIKit
import Foundation
import Darwin
protocol Shape {
func area()

class Reactange: Shape {


var length = 10
var width = 50

func area() {
print("Area is \(length * width)")
}

class Square: Shape {


var length = 50

func area() {
print("Area is \(length * length)")
}

let obj = Reactange()


[Link] = 30
[Link]()

FAT protocol
protocol Animals: Mamels {
func hunt()
}

class Person: Human {


func thinks() {
<#code#>
}

func sleep() {
<#code#>
}

func eat() {
<#code#>
}

}
class Lion: Animals {
func hunt() {
<#code#>
}

func sleep() {
<#code#>
}

func eat() {
<#code#>
}

}
Dependency Inversion

protocol Operations {
func saveInfo()
}

class DatabaseOperations: Operations {

func saveInfo() {
print("Info saved")
}

class LoginVC {

var db: DatabaseOperations?

init(db: DatabaseOperations) {
[Link] = db
}
func getInfo() {
db?.saveInfo()
}

let obj = LoginVC(db: DatabaseOperations())


[Link]()

You might also like