0

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?

Noah Wilder
  • 1,656
  • 20
  • 38
  • 1
    What you are looking for is __namespaces__. Have a look at the related question: [How to use namespaces in Swift](https://stackoverflow.com/questions/24002821/how-to-use-namespaces-in-swift). However, AFAIK Swift doesn't support defining namespaces without creating a new type such as C++ (which is what you seem to mean by "grouping"), so what you are looking for is not possible. – Dávid Pásztor Mar 05 '18 at 00:07

1 Answers1

2

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
        }
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571