0

Task: Return current value of variable and increase itself after go out function.

Java implementation

class A {
    public int x = 0;

    public int changeVal() {
        return x++;
    }
}

Usage:

A a = new A();
a.x;              //output is 0
a.changeVal();    //output is 0    
a.x;              //output is 1

The same implementation converted to Swift:

class A {
    var x : Int = 0

    func changeVal() -> Int {
        let t = x               
        x += 1

        return t
    }
}

Is there any shorter way to achieve this without those two lines?

let t = x               
x += 1
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
Tuan Huynh
  • 566
  • 4
  • 13
  • Swift used to have the prefix and postfix `++` and `--` operators. They were removed specifically because they don't want you to write code like this. The 2 line version is much clearer. – Sweeper Oct 08 '17 at 10:51
  • 2
    I'm not sure I understand your question "*Can simple for 2 rows or any other solution?*", but compare https://stackoverflow.com/q/36185088/2976878; you can use `defer` here. – Hamish Oct 08 '17 at 10:56

0 Answers0