Proposal: instance variable declarations inside methods


(Amir Michail) #1

For example:

class A {
  var c = 0
  func getAndIncCount() -> Int {
    let v = c
    c++
    return v
  }
}

Could be refactored as:

class A {
  func getAndIncCount() -> Int {
    instance var c = 0 // this instance variable for class A is only accessible in this method
    let v = c
    c++
    return v
  }
}


(Myles La Verne Schultz) #2

Isn't this already something one can do with closures?

Myles

···

Sent from my iPhone

On Feb 14, 2016, at 12:04 PM, Amir Michail via swift-evolution <swift-evolution@swift.org> wrote:

For example:

class A {
var c = 0
func getAndIncCount() -> Int {
   let v = c
   c++
   return v
}
}

Could be refactored as:

class A {
func getAndIncCount() -> Int {
   instance var c = 0 // this instance variable for class A is only accessible in this method
   let v = c
   c++
   return v
}
}

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


(Alexey Demedetskiy) #3

-1 from me.

This feature will add even more ways to introduce side effects.
It will push people to quick and dirty solutions instead of nice decomposition.

If this state belongs just to this function - mb it is better to move function to separate unit? (class or struct)
Other valid option will be using memoization technics.

Also, it will complicate rules for extensions - as soon as instance variable cannot be introduced outside of
main unit declaration.

If you have a lot of code that would benefit from this feature - consider decomposition option. And split single class into several instances.

···

For example:

class A {
var c = 0
func getAndIncCount() ->Int {
let v = c
c++
return v
}
}

Could be refactored as:

class A {
func getAndIncCount() ->Int {
instance var c = 0 // this instance variable for class A is only accessible in this method
let v = c
c++
return v
}
}