0
0
iOS Swiftmobile~10 mins

Repository pattern 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 for the repository.

iOS Swift
protocol UserRepository {
    func fetchUser(id: Int) -> [1]
}
Drag options to blanks, or click blank then click option'
AInt
BUser?
CString
DVoid
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a String or Int instead of a User object.
Using Void as return type which means no value returned.
2fill in blank
medium

Complete the code to implement the repository class conforming to the protocol.

iOS Swift
class UserRepositoryImpl: UserRepository {
    func fetchUser(id: Int) -> [1] {
        // Implementation
        return nil
    }
}
Drag options to blanks, or click blank then click option'
AInt
BString
CUser?
DVoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different return type than the protocol.
Forgetting to return a value.
3fill in blank
hard

Fix the error in the repository method signature to match the protocol.

iOS Swift
func fetchUser(id: Int) -> [1] {
    // code
}
Drag options to blanks, or click blank then click option'
AUser?
BString
CVoid
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Returning non-optional User which causes mismatch.
Using unrelated types like String or Void.
4fill in blank
hard

Fill both blanks to create a repository method that fetches a user by id and returns a default if not found.

iOS Swift
func fetchUserOrDefault(id: Int) -> [1] {
    return fetchUser(id: id) [2] User(name: "Guest")
}
Drag options to blanks, or click blank then click option'
AUser
B??
C!
D->
Attempts:
3 left
💡 Hint
Common Mistakes
Using ! which force unwraps and can crash.
Using -> in place of ?? which is invalid.
5fill in blank
hard

Fill all three blanks to define a repository protocol with a save method and implement it in a class.

iOS Swift
protocol UserRepository {
    func save(user: [1]) -> [2]
}

class UserRepositoryImpl: UserRepository {
    func save(user: [3]) -> Bool {
        // Save logic
        return true
    }
}
Drag options to blanks, or click blank then click option'
AUser
BBool
CUser?
DVoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using optional User? as parameter which is not required here.
Returning Void instead of Bool.
Mismatching parameter types between protocol and class.