Questions based on higher-order functions — Part I
Question 1: Given an array of user objects, each containing a name and age property, how would you filter out users under the age of 30 using higher-order functions?
Answer:
struct User {
let name: String
let age: Int
}
let users = [
User(name: "Alice", age: 25),
User(name: "Bob", age: 35),
User(name: "Charlie", age: 28)
]
let youngUsers = users.filter { $0.age < 30 }
print(youngUsers)
Question 2: Suppose you have an array of product objects, each containing a name, price, and quantity property. How would you calculate the total value of all products in the array using higher-order functions?
Answer:
struct Product {
let name: String
let price: Double
let quantity: Int
}
let products = [
Product(name: "iPhone", price: 999.99, quantity: 2),
Product(name: "MacBook Pro", price: 1999.99, quantity: 1),
Product(name: "AirPods", price: 199.99, quantity: 3)
]
let totalValue = products.reduce(0) { $0 + ($1.price * Double($1.quantity)) }
print(totalValue)
Question 3: You have an array of student objects, each containing a name and a list of test scores. How would you calculate the average score for each student using higher-order functions?
Answer:
struct Student {
let name: String
let testScores: [Int]
}
let students = [
Student(name: "Alice", testScores: [85, 90, 88]),
Student(name: "Bob", testScores: [75, 80, 82]),
Student(name: "Charlie", testScores: [95, 92, 88])
]
let averageScores = students.map { student in
let averageScore = Double(student.testScores.reduce(0, +)) / Double(student.testScores.count)
return (student.name, averageScore)
}
print(averageScores)
Question 4: Suppose you have an array of book objects, each containing a title, author, and publication year. How would you sort the books by their publication year in ascending order using higher-order functions?
Answer:
struct Book {
let title: String
let author: String
let publicationYear: Int
}
let books = [
Book(title: "Book A", author: "Author A", publicationYear: 2005),
Book(title: "Book B", author: "Author B", publicationYear: 2010),
Book(title: "Book C", author: "Author C", publicationYear: 2000)
]
let sortedBooks = books.sorted { $0.publicationYear < $1.publicationYear }
print(sortedBooks)
Question 5: Given an array of employee objects, each containing a name and a salary property, how would you find the highest-paid employee using higher-order functions?
Answer:
struct Employee {
let name: String
let salary: Double
}
let employees = [
Employee(name: "Alice", salary: 50000),
Employee(name: "Bob", salary: 60000),
Employee(name: "Charlie", salary: 55000)
]
if let highestPaidEmployee = employees.max(by: { $0.salary < $1.salary }) {
print("The highest-paid employee is \(highestPaidEmployee.name) with a salary of \(highestPaidEmployee.salary)")
} else {
print("No employees found")
}