You have a request ? Contact Us Join Us

Advanced Programming in Swift | Coursera Quiz Answers

Discover the answer key in Coursera's Advanced Programming in Swift for Meta iOS Developer Professional Certificate.
Estimated read time: 28 min
Coursera: Advanced Programming in Swift Answers
Advanced Programming in Swift | Coursera Meta

In the core of every exceptional iOS application lies a deep grasp of the Swift programming language. To advance your expertise, enroll in Advanced Programming in Swift. Delve into Swift's advanced custom data types, refine code organization strategies, master error handling for enhanced program efficiency, and delve into functional programming principles through higher-order functions such as map, filter, and reduce. Additionally, gain insights into implementing unit tests to ensure the robust functionality of your applications.

By completing this course, you'll gain hands-on experience in building functionalities commonly found in apps with extensive item lists. You'll explore advanced programming principles, including employing higher-order functions for collection processing and constructing lists within Xcode. Upon finishing the course, you'll be equipped to:

  • Develop custom data types, including enumerations and sets.
  • Efficiently organize and optimize code using subclassing, inheritance, typecasting, and polymorphism.
  • Implement access control to regulate code restrictions.
  • Create flexible code structures using optional and required protocols.
  • Utilize delegation to transfer control and responsibilities between instances.
  • Implement robust error handling techniques, including throwable functions and error catching.
  • Understand recursion and its practical applications.
  • Apply higher-order functions like map, filter, and reduce effectively.
  • Ensure application reliability through comprehensive unit testing.

This course targets intermediate learners aiming to prepare for a career in iOS development, requiring a solid foundation in Swift and SwiftUI fundamentals for successful participation.


Notice!
Always refer to the module on your course for the most accurate and up-to-date information.

Attention!
If you have any questions that are not covered in this post, please feel free to leave them in the comments section below. Thank you for your engagement.

Module quiz: Advanced data types 

1. The code below demonstrates two separate ways to declare a set. 
var cities: Set = ["Cairo", "London", "Paris"]
var cities2: Set<String> = ["Moscow", "Hanoi", "Zurich"]
  • True
  • False
2. What is the output of the code? 
var numbersA : Set = [100, 102, 103]
var numbersB : Set = [101, 103, 100]
let numbers = numbersA.union(numbersB)
print(numbers)
  • [100, 101, 103, 101]
  • [100, 100, 102, 103]
  • [103, 102, 103, 101]
  • [100, 102, 103, 101]
3. What is the output of the following code? 
enum Week: Int, CaseIterable {
  case Monday = 1
  case Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
for day in Week.allCases {
  print("\(day) is day \(day.rawValue) of the week")
}
  • No error but no output
  • An error is thrown because only Monday has a raw value.
  • Monday is day 1 of the week
    Tuesday is day 2 of the week
    Wednesday is day 3 of the week
    Thursday is day 4 of the week
    Friday is day 5 of the week
    Saturday is day 6 of the week
  • Monday is day 1 of the week
4. Which of the following can be applied to an enum? Select all that apply.
  • Functions
  • Raw values
  • Computed properties
5. What is the raw type of the following enum? 
enum PastaTypes {
    case spaghetti
    case penne
    case ravioli
    case rigatoni
}
  • Double
  • String
  • Int
  • None of the above
6. What will the output of the following code be?
enum PastaTypes: Int {
    case spaghetti
    case penne
    case ravioli
    case rigatoni
}
Print(PastaTypes.penne.rawValue)
  • 0
  • 1
  • 2
  • None of the above
7. To use allCases property in your code, which protocol must an enum conform to?
  • CaseIterable
  • Equatable 
  • Hashable 
8.What will the output of the following code be? 
var listOfNumbers = Set<Int>()
listOfNumbers.insert(1)
listOfNumbers.insert(5)
listOfNumbers.insert(8)
listOfNumbers.insert(3)
ListOfNumbers.insert(1)
print(listOfNumbers.count)
  • 5
  • 4
  • None of the above. 
9. Which of the statements is true about sets?
  • Contains elements that have key-value pairs where each key must be unique.
  • Can only store distinct unordered values of the same type.
  • Contains elements in a collection that don’t necessarily need to be unique.
10. In the scenario when there is a large amount of data expected and performance is of a crucial importance, which of the below collections would you want to use to improve the performance of your application? 
  • Array
  • Set

Module quiz: Code organization

1. The following class declaration is a base class.
class Vehicle { 
  • True
  • False
2. Given the following code:
class Vehicle {
}
class Truck: Vehicle {
}
Which class is the subclass?
  • Truck
  • Vehicle
3. Given the following code in a SecretFood.swift source file:
class SecretFood {
    private var secretIngredients: [String] = []
}
class Chef {
    func cookSecretFood(_ secretFood: SecretFood) {
        print(secretFood.secretIngredients)
    }
}
Will the code compile successfully?
  • Yes
  • No
4. Which of the following options list the access-level modifiers from least restrictive to most restrictive?
  • private, fileprivate, internal, public, open
  • internal, private, fileprivate, public, open
  • open, public, internal, fileprivate, private
5. Which of the following operators guarantees casting an instance into another type will always succeed?
  • as?
  • ==
  • as!
  • is
6. Given the following code:
class Spaghetti {
    func fetchIngredients() {
        print("Spaghetti Ingredients")
    }
}
class SpaghettiMeatball: Spaghetti {
    override func fetchIngredients() {
        print("BBB")
        super.fetchIngredients()
        print("AAA")
    }
}
let spaghettiMeatball = SpaghettiMeatball()
spaghettiMeatball.fetchIngredients()
What is the console output?
  • AAA
    BBB
    Spaghetti Ingredients
  • BBB
    Spaghetti Ingredients
    AAA
  • Spaghetti Ingredients
  • Spaghetti Ingredients
    BBB
    AAA
7. Which of the following lines of code is a valid protocol property requirement declaration?
  • let propertyIdentifier: Int
  • var propertyIdentifier: Int { set }
  • var propertyIdentifier: Int { get }
8. Which of the following lines of code is a valid protocol method requirement declaration?
  • func methodIdentifier() { get }
  • func methodIdentifier() -> String {}
  • func methodIdentifier() -> String
9. Given the following protocol:
protocol Employee {
    var daysWorking: Int { get set }
}
Which of the following struct declaration is valid?
struct Waiter: Employee {
    var daysWorking: Int
}

struct Waiter: Employee {
    var daysWorking: Double
}

struct Waiter: Employee {
    let daysWorking: Int
}
10. How many protocols can a protocol inherit at most?
  • 0
  • 1
  • Unlimited
11. Given the following protocol:
protocol ProtocolIdentifier {
    func methodIdentifier(parameter: Int) -> Int
    var propertyIdentifier: Int { get }
}
Which of the following code blocks declares the methodIdentifier method as an optional requirement?
@objc protocol ProtocolIdentifier {
    @objc optional func methodIdentifier(parameter: Int) -> Int
    var propertyIdentifier: Int? { get }
}

@objc protocol ProtocolIdentifier {
    func methodIdentifier(parameter: Int) -> Int
    @objc optional var propertyIdentifier: Int { get }
}

@objc protocol ProtocolIdentifier {
    @objc func methodIdentifier(parameter: Int) -> Int
    var propertyIdentifier: Int { get }
}

protocol ProtocolIdentifier {
    func methodIdentifier(parameter: Int) -> Int
    @objc optional var propertyIdentifier: Int { get }
}
12. Given the following code:
protocol Driver {
    var name: String { get }
    func driveToDestination(_ destination: String, with food: String)
}
class DeliveryDriver: Driver {
    let name: String
    init(name: String) {
        self.name = name
    }
    func driveToDestination(_ destination: String, with food: String) {
        print("\(name) is driving to \(destination) to deliver \(food).")
    }
}
class LittleLemon {
    var deliveryDriver: Driver?
    func getDriverName() {
        if let name = deliveryDriver?.name {
            print("Driver name: \(name)")
        } else {
            print("No delivery driver found.")
        }
    }
}
let elisa = DeliveryDriver(name: "Elisa")
let littleLemon = LittleLemon()
littleLemon.deliveryDriver = elisa
littleLemon.getDriverName()
What is the console output?
  • No delivery driver found.
  • Driver name: Elisa
13. Both a struct and a class can adopt protocols.
  • True
  • False

Module quiz: Error handling, functional programming and testing

1. What does the keyword throws do?
  • It can be used to throw an error from a throwable function.
  • Function can be marked with it to make it a throwable-function.
  • It is used to declare an error.
2. Will the following code run without issues?
do {
 print("hello")
}
catch {
 print("Error caught")
}
catch {
 print("Another error caught")
}
  • Yes, code runs with no issues
  • Yes, but first catch block will be executed.
  • No, there cannot be two catch blocks after each other.
3. Identify the error in the following code:
if let result = try! throwableFunction() {}
  • Throwable function must be called inside a do-catch statement.
  • Nothing wrong with the code.
  • try! Cannot be in if-let statement as it does not return an optional value.
4. Can the following class be thrown as an error?
class MyClass: NSError {
}
  • No, as classes cannot be thrown as errors.
  • No, as it does not extend Error protocol.
  • Yes
5. What will the output of the following function be?
func output() {
 defer { print(1) }
 print("2")
 defer { print(3) }
 print(4)
}
  • 4
    3
    2
    1
  • 1
    2
    3
    4
  • 2
    4
    3
    1
6. What is a multi-recursion?
  • When a function has a call to itself in the end of its implementation.
  • It’s when function has multiple call to itself in its implementation.
  • When a function has a call to itself in the beginning of its implementation.
7. Which is the following is used in Swift when implementing code in a functional way?
  • throwable function
  • do-catch
  • closure
8. Which of the following functions would you use to iterate over all elements of the array?
  • forEach
  • map
  • reduce
9.  What is unit testing in Swift?
  • Unit testing is evaluating user interface 
  • Unit test is verifying a small pieces of code do what they are supposed to do.
  • Unit testing is evaluating the compatibility of software across multiple different devices.
10. Mock can be used instead of a fake.
  • True
  • False

Final graded quiz: Advanced Programming in Swift

1. Which of the following keywords creates a reference type?
  • struct
  • class
  • enum
2. Which of the following code will compile?
class Wallet { 
    let dollars: Double? = nil 

class Wallet { 
    var dollars: Double = “10” 
}

class Wallet { 
    let dollars: Double?
}

class Wallet { 
    let dollars: Double 
    init(_ dollars: Double) { 
        dollars = dollars 
    } 
3. Given the following code:
let prices = [ 
    2.99,
    2.99,
    5.99,
    5.99,
    5.99,
    17.99
]
print(Set(prices)) 
Which of the following options is a valid console output?
  • None
  • [2.99, 2.99, 5.99, 5.99, 5.99, 17.99]
  • [5.99, 17.99, 2.99]
4. Which of the following code options will compile successfully?
struct Book {
    var title = "N/A"
    mutating func updateBookTitle(_ title: String) {
        self.title = title
    }
}
let book = Book()
book.updateBookTitle("Secret Ingredients")



5. Which of the following access-level modifiers is suitable for subclassing a custom data type between modules?
  • open
  • private
  • internal
  • public
  • fileprivate
6. Given the following code:

7. Given the code declarations:
protocol FoodDelivery {
    func deliverFood()
}
struct Car: FoodDelivery {
    func deliverFood() {
        print("Deliver food by car")
    }
}
class Restaurant {
    var delegate: FoodDelivery?
    func delegateDelivery() {
        if let delegate = delegate {
            delegate.deliverFood()
            return
        }
        print("No delegate found.")
    }
}
And the following desired console output:
Deliver food by car
Which of the following block of codes will produce the desired console output? Select all that apply.
let restaurant = Restaurant()
restaurant.delegate = Car()
restaurant.delegate?.deliverFood()

let restaurant = Restaurant()
restaurant.delegateDelivery()

let restaurant = Restaurant()
restaurant.delegate?.deliverFood()
restaurant.delegate = Car()

let restaurant = Restaurant()
restaurant.delegate = Car()
restaurant.delegateDelivery()
8. Given the following code:
let berries = [
    "strawberry",
    "blueberry",
    "grape",
    "goji"
]
let result = berries
    .filter { $0.count > 5 }
    .map { "healthy \($0)\n" }
    .reduce("Berries:\n") { $0 + $1 }
print(result)
What will the console output?
  • healthy strawberry
    healthy blueberry
  • Berries:
    strawberry
    blueberry
    grape
    goji
  • Berries:
    healthy strawberry
    healthy blueberry
    healthy grape
    healthy goji
  • strawberry
    blueberry
    grape
    goji
  • Berries:
    healthy strawberry
    healthy blueberry
9. Given the following code:
class Berry {
}
class Blueberry: Berry {
}
class Strawberry: Berry {
}
let berries = [Berry(), Blueberry(), Strawberry()]
for berry in berries {
    if berry is Berry {
        print("Berry")
    }
    if berry is Blueberry {
        print("Blueberry")
    }
    if berry is Strawberry {
        print("Strawberry")
    }
What will the console output?
  • Berry
    Berry
    Berry
    Blueberry
  • Berry
    Blueberry
    Strawberry
  • Berry
    Berry
    Blueberry
    Berry
    Strawberry
10. Which of the following test methods will pass? Select all that apply.
func test() {
    let sum = 8 + 7 + 5
    XCTAssertEqual(sum, 20)
}

func test() {
    XCTAssert(str.isEmpty)
    let str = "hello"
}

func test() {
    var indices: [Int] = []
    for i in 0..<5 {
        indices.append(i)
    }
    XCTAssert(indices.count == 4)
}

func test() {
    let product = 10 * 8
    XCTAssertEqual(product, 80)
}

Related Articles

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.