Home > Back-end >  How to create class with public method that prints three odd numbers starting from 11 in Swift?
How to create class with public method that prints three odd numbers starting from 11 in Swift?

Time:12-29

I received following task: make Class with name OddNumber that accepts number to its constructor from which it starts writing three odd numbers - starting from number 11. This Class shall have one public method with name getNextNumber - every time it is called, it returns next odd number (so has to remember the last one for returning the next one). Pseudo code from the task:

object = new OddNumber(11)
for i in 1...3
    print(object.getNextNumber())

I could not find solution by myself, only did "mirror" one code example where classes are explained. Can you help, how can be the code simplied / made shorter?

class Range {
    var numberX = 9

    func printNumber() {
        print(numberX)
    }

    func getNextNumber(increase two: Int) {
        numberX  = two
    }
}

class Counter {
    var range: Range?
    func countUp() {
        if range != nil {
            print("range exists")
        }
    }
}

class OddNumber: Counter {
    override func countUp() {
        range?.getNextNumber(increase:  2)
    }
}

var myRange = Range()

let output = OddNumber()
output.range = myRange

for _ in 1...3 {
    output.countUp()
    output.range?.printNumber()
}

CodePudding user response:

What you need is to first check if the last value is multiple of 2. If true just increase the last value by one otherwise increase it by two and return it. Something like:

class OddNumber {
    var lastValue: Int
    init(_ lastValue: Int) {
        self.lastValue = lastValue
    }
    public func getNextNumber() -> Int {
        lastValue  = lastValue.isMultiple(of: 2) ? 1 : 2
        return lastValue
    }
}

Playground testing:

let object = OddNumber(11)
for _ in 1...3 {
    print(object.getNextNumber())  // 13, 15, 17
}

Another option is to add the result of the last value remainder operator by two (also known as modulo operator) increased by one:

lastValue  = lastValue % 2   1
  • Related