Complete the code to declare a protocol for the repository.
protocol UserRepository {
func fetchUser(id: Int) -> [1]
}The repository protocol should define a method that returns an optional User object when fetching by id.
Complete the code to implement the repository class conforming to the protocol.
class UserRepositoryImpl: UserRepository { func fetchUser(id: Int) -> [1] { // Implementation return nil } }
The implementation must match the protocol signature, returning an optional User.
Fix the error in the repository method signature to match the protocol.
func fetchUser(id: Int) -> [1] {
// code
}The method must return an optional User (User?) to match the protocol and handle missing users.
Fill both blanks to create a repository method that fetches a user by id and returns a default if not found.
func fetchUserOrDefault(id: Int) -> [1] { return fetchUser(id: id) [2] User(name: "Guest") }
The method returns a User and uses the nil-coalescing operator ?? to provide a default User if fetchUser returns nil.
Fill all three blanks to define a repository protocol with a save method and implement it in a class.
protocol UserRepository {
func save(user: [1]) -> [2]
}
class UserRepositoryImpl: UserRepository {
func save(user: [3]) -> Bool {
// Save logic
return true
}
}The protocol defines a save method that takes a User and returns a Bool indicating success. The class implements the same signature.