iOS Interview Questions and Answers for Senior Developers Part 5 - Architecture & Design Patterns

1. What is the idea behind the MVC architecture?

MVC stands for Model View Controller.

the View represents the User Interface layer

the Model represents the Data Access layer

the Controller represents the Business Logic layer

The controller is the mediator between the view and the model. The model and the view know nothing about the controller or each other. They communicate with the outside world by sending a notification about some event, for example by calling a callback method or using the observer pattern.

2. Which alternative architectures do you know? Explain one of them.

Examples of alternative architectures are MVVM (Model-View-ViewModel), MVP (Model-View-Presenter) or VIPER (View-Interactor-Presenter-Entity-Routing).

The MVVM architecture consists of a Model, a View and a ViewModel. The View and the Model are already familiar from MVC and have the same responsibilities. The mediator between them is represented by the View Model.

In theory, you could say that MVC and MVVM are the same architectures with different namings for the mediator. In practice however, many developers ran into the Massive View Controller problem with Apple's MVC by using a UIViewController as the Controller. But UIViewControllers are too involved in the View’s life cycle so it’s hard to separate them.

The main difference between the ViewModel from MVVM and the Controller from MVC is that the ViewModel is defined to be UIKit independent. With MVVM, the UIViewController becomes part of the View.

3. Explain the observer design pattern. What options do you have to implement the observer design pattern in Swift?

The observer design pattern is characterized by two elements:

A value being observed (an observable), which notifies all observers if a change happens.

An observer, who subscribes to changes of the observable.

Existing solutions of the observer pattern in iOS are:

Notifications

Key-Value Observing

Publishers (observables) and Subscribers (observers) of the Combine Framework

4. What is a singleton design pattern? When would you use and when would you avoid singletons?

The singleton design pattern ensures that only one instance exists for a given class.

In Swift, this pattern is easy to implement:

classChocolateFactory {static letshared:ChocolateFactory= {letinstance =ChocolateFactory()returninstance    }()}

A singleton is useful when exactly one object is needed to coordinate actions across the app. A good example is Apple's UIApplication.shared instance, because within the app there should be only one instance of the UIApplication class.

The singleton pattern is easy to overuse though. In most cases, it can be replaced with dependecy injection, for example by passing the dependencies into the object's initializer. With the dependecy injection approach, modularity and testability of the code improves. It becomes a lot easier to mock and fake passed in dependencies for unit tests.

5. Name some other design patterns you know and give a short explanation.

Examples of other design patterns are the delegate design pattern, the factory design pattern and the facade design pattern.

The delegate design pattern allows an object to communicate back to its owner in a decoupled way. This way, an object can hand off (delegate) some of its responsibilities to its owner. A common way to define a delegate is by using protocols. The delegate design pattern is an old friend on Apple's platforms. Examples are UITableViewDelegate, UICollectionViewDelegate, UITextViewDelegate etc.

The factory design pattern is a way to encapsulate the implementation details of creating objects. It separates the creation from the usage of the objects. The initialization is done in a central place. So when the initialization logic of certain objects changes, you don't need to change every creation in the whole project.

Example of a simple factory:

classChocolateFactory {static funcproduceChocolate(of type:ChocolateType) ->Chocolate{switchtype {case.dark:returnDarkChocolate()case.raw:returnRawChocolate()        }    }}

The facade design pattern provides a simpler interface for a complex subsystem. Instead of exposing a lot of classes and their APIs, you only expose one unified API. The facade pattern improves the readability and usability. It also decouples and reduces dependencies. If implementation details under the facade change, the facade can retain the same API while things change behind the scenes.

For example, you could create a ChocolateShopService and hide all the http requests and persistence details behind it.

classChocolateShopService {funcgetChocolates() -> [Chocolate] {ifisOnline {returnhttpClient.get("/api/chocolates")        }else{returnlocalStore.getChocolates()        }    }}

6. How can you avoid the problem of so called spaghetti code?

The term spaghetti code is used for unstructured and difficult-to-maintain code. To avoid spaghetti code it is important to constantly think about building clean, reusable and testable components.

Those qualities can be achieved by focusing on decoupling and separation of concerns, for example through dependency injection, generic solutions, protocol oriented programming and by using appropriate design patterns.

7. What is your undestanding of reactive programming? What possibilities do you have on iOS?

Reactive programming is programming with asynchronous observable streams.

A stream (also called an observable) can emit either a value of some type, an error or a completed event. You can listen to a stream by subscribing to it (observing it).

You can observe those async streams and react with various functional methods when a value is emitted. You can merge two streams, filter a stream to get another one or map data values from one stream to another new one.

To use reactive programming in iOS you can use the Combine framework that was introduced at WWDC 2019. Or you can use a third party library like RxSwift.

8. What is TDD? What benefits and limitations does it have?

TDD stands for test driven development. The idea behind it is to write tests before writing code.

Benefits Test driven development leads to higher code test coverage. Also, the tests provide documentation about how the app is expected to behave. TDD helps to build modularized code, because it requires the developer to think in small units that can be written and tested independently. This leads to decoupled focused components and clean interfaces.

Limitations TDD only focuses on unit tests, it does not cover UI or integration tests. So additional tests are needed to make sure that the app is working properly. When using TDD, code design decisions become even more important than they already are, because tests become part of the maintenance overhead. Badly written tests are prone to failure and expensive to maintain.

9. What are good use cases to use extensions in Swift?

An extension in Swift is a powerful way to add new functionality to existing classes, structures or enums without modifying its code.

For example, accessing an array element leads to a crash if the specified index doesn't exist. To avoid a crash, you could wrap every access in an if-block. A more elegant solution with an extension looks like this:

extensionArray{/// Returns the element at the specified index if it is within bounds, otherwise nil.subscript(safe index:Index) ->Iterator.Element? {returnindices.contains(index) ?self[index] :nil}}// Usage:letvalue = someArray[safe:6]

10. What is your understanding of protocol oriented programming?

Protocol oriented programming is a concept of designing your code base by using protocols. In Swift, protocols provide an extensive set of features, so they have become a powerful way of managing code complexity and creating modular testable components.

A protocol allows you to group similar methods and properties for classes, structs and enums. In contrast to class inheritence, objects can conform to multiple protocols.

Like classes, protocols also support inheritence. For example, the Comparable protocol inherits from Equatable in Swift. You can also combine two protocols together to build new protocols, for example:

typealiasCodable =Decodable&Encodable

To implement default behaviour with protocols, you can use protocol extensions.

protocolChocolate {varhasSugar:Bool{get}}extensionChocolate{varhasSugar:Bool{return true}}structDarkChocolate:Chocolate{// hasSugar is true by default}

This way, all types that conform to the same protocol will get the default behaviour.

11. Explain dependency injection. What types of dependency injection do you know?

Dependency injection is a technique where an object gets its dependencies from the outside instead of creating the dependency internally. With dependency injection, the objects get less coupled, more reusable and more testable, it gets a lot easier to mock objects for unit tests.

Dependency injection can be implemented in different ways, for example an initializer-based or a property-based dependency injection.

There are also some external libraries like Swinject or Dip that centralize the managing of dependencies.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,384评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,845评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,148评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,640评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,731评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,712评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,703评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,473评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,915评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,227评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,384评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,063评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,706评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,302评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,531评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,321评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,248评论 2 352

推荐阅读更多精彩内容

  • 越来越多的人在学习iOS课程,起初我自己是通过国内的一些网站学习,但是视频教程更新慢。后来在Youtube上看视频...
    东东隆东抢阅读 4,095评论 0 9
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,519评论 16 22
  • 创业是很多人的梦想,多少人为了理想和不甘选择了创业来实现自我价值,我就是其中一个。 创业后,我由女人变成了超人,什...
    亦宝宝阅读 1,805评论 4 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,562评论 0 11
  • 可爱进取,孤独成精。努力飞翔,天堂翱翔。战争美好,孤独进取。胆大飞翔,成就辉煌。努力进取,遥望,和谐家园。可爱游走...
    赵原野阅读 2,724评论 1 1