Search code examples
swiftfunctionstructswift-extensions

How to Add Another Level to an Extension (categorize like extensions)


I want to take a bunch of like functions/mutating functions inside an extension and store (categorize) them under one name. So let's say I have this:

extension Int {

    mutating func addTen() {
        self = self + 10
    }

    mutating func subtractTen() {
        self = self - 10
    }

    mutating func multiplyTen() {
        self = 10 * self
    }

    mutating func divideTen() {
        self = self / 10
    }

}

So now if I want to increase the value of a number by ten I can do this:

var number : Int = 27
number.addTen() // Now number is equal to 37

But what I want to do is to store all of these extensions under the name: myOperations.

So ideally I would like to access my extensions like this:

var number1 = 20
var number2 = 20
var number3 = 20
var number4 = 20

number1.myOperations.addTen() //change to 30
number2.myOperations.subtractTen() //change to 10
number3.myOperations.multiplyTen() //change to 200
number4.myOperations.divideTen() //change to 2 

I tried to accomplish this by doing this:

extension Int {

    struct myOperations {

        mutating func addTen() {
            self = self + 10
        }

        mutating func subtractTen() {
            self = self - 10
        }

        mutating func multiplyTen() {
            self = 10 * self
        }

        mutating func divideTen() {
           self = self / 10
        }
    }
}

But I got the error: Binary operator '+' cannot be applied to operands of type 'Int.myOperations' and 'Int'

How do I put all of the extensions under a grouping called: myOperations?


Solution

  • Note that it is Swift convention to name your structures starting with an uppercase letter. If you would like to mutate the integer you need a method instead of a structure and make it mutating. Regarding your operations what you need is an enumeration and pass it to your mutating method. It would look like this:

    number1.operations(.addTen)
    

    extension Int {
        enum Operation {
            case addTen, subtractTen, multiplyTen, divideTen
        }
        mutating func operations(_ operation: Operation) {
            switch operation {
            case .addTen:
                self += 10
            case .subtractTen:
                self -= 10
            case .multiplyTen:
                self *= 10
            case .divideTen:
                self /=  10
            }
        }
    }