0
0
iOS Swiftmobile~10 mins

Mock objects and protocols in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a protocol named Logger with a log function.

iOS Swift
protocol Logger {
    func [1](message: String)
}
Drag options to blanks, or click blank then click option'
Awrite
Bprint
Csend
Dlog
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name that does not describe logging, like 'print' or 'send'.
2fill in blank
medium

Complete the code to create a mock class MockLogger that conforms to Logger protocol.

iOS Swift
class MockLogger: Logger {
    var messages: [String] = []
    func [1](message: String) {
        messages.append(message)
    }
}
Drag options to blanks, or click blank then click option'
Asend
Bprint
Clog
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than the protocol requires.
3fill in blank
hard

Fix the error in the test function to verify the mock logger recorded the message.

iOS Swift
func testLogging() {
    let mockLogger = MockLogger()
    mockLogger.log(message: "Test message")
    assert(mockLogger.[1].count == 1)
}
Drag options to blanks, or click blank then click option'
Amessages
BlogMessages
Clogs
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using a property name that does not exist in MockLogger.
4fill in blank
hard

Fill both blanks to create a protocol and a mock class that counts calls.

iOS Swift
protocol [1] {
    func fetchData()
}

class MockFetcher: [2] {
    var callCount = 0
    func fetchData() {
        callCount += 1
    }
}
Drag options to blanks, or click blank then click option'
ADataFetcher
BLogger
CDataFetcher
DLogger
Attempts:
3 left
💡 Hint
Common Mistakes
Using mismatched protocol and class names.
5fill in blank
hard

Fill all three blanks to define a protocol, a mock class, and a test verifying call count.

iOS Swift
protocol [1] {
    func save(data: String)
}

class MockSaver: [2] {
    var saveCalls = 0
    func save(data: String) {
        saveCalls += 1
    }
}

func testSave() {
    let mock = MockSaver()
    mock.save(data: "Hello")
    assert(mock.[3] == 1)
}
Drag options to blanks, or click blank then click option'
ASaver
BMockSaver
CsaveCalls
DSaver
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect protocol or property names in the test.