Fresher Training—iOS Swift Day 3

by NhatHM
577 views

Today topic:

  • Access Control & Code Organization
  • Custom Operators, Subscripts & Keypaths
  • Pattern Matching
  • Error Handling

Thao khảo: Swift—Advanced control flow

Exercises:

Exercise 01: SINGLETON
  • A singleton is a design pattern that restricts the instantiation of a class to one object.
  • Use access modifiers to create a singleton class Logger. This Logger should:
  • Provide shared, public, global access to the single Logger object.
  • Not be able to be instantiated by consuming code.
  • Have a method log() that will print a string to the console.

Điểm: 2

Exercise 02: STACK
  • Declare a generic type Stack. A stack is a LIFO (last-in-first-out) data structure that supports the following operations:
  • peek: returns the top element on the stack without removing it. Returns nil if the stack is empty.
  • push: adds an element on top of the stack.
  • pop: returns and removes the top element on the stack. Returns nil if the stack is empty.
  • count: returns the size of the stack.
  • Ensure that these operations are the only exposed interface. In other words, additional properties or methods needed to implement the type should not be visible.

Điểm: 2.5

Exercise 03: SUBSCRIPT
extension Array {
    subscript(index: Int) -> (String, String)? {
        guard let value = self[index] as? Int else {
            return nil
        }
        
        switch (value >= 0, abs(value) % 2) {
        case (true, 0):
            return ("positive", "even")
        case (true, 1):
            return ("positive", "odd")
        case (false, 0):
            return ("negative", "even")
        case (false, 1):
            return ("negative", "odd")
        default:
            return nil
        }
    }
}

What wrong with this code? How to fix?

Điểm: 1.5

Exercise 04: ERROR HANDLING

Write a throwing function that converts a String to an even number, rounding down if necessary.

Điểm: 2

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.