Proposal: External variable in extension


(Kevin) #1

Currently possible to add extension to class, so we can separate the implementation to different class files. In some situation this still have some limitations,
For example:

public class Racer {

    public var name:String

    public init(name:String) {
        self.name = name
    }
}

public extension Racer {

    public var winTimes:Int {
        // requires access local variable
    }

    public func win() {
        // need to update local variable
    }
}

the method in the extension sometimes need add another variable to store values, if you are extending the system class, that will be very hard to make this happen

So I am thinking, can we add another namespace “external” besides “public, private, internal”, with this we can define a “external var” inside the extension scope.
the variable needs a default value, and only can accessed in the extension scope, the implementation for the example will like this:

public class Racer {

    public var name:String

    public init(name:String) {
        self.name = name
    }
}

public extension Racer {

    external var _winTimes:Int = 0

    public var winTimes:Int {
        return _winTimes
    }

    public func win() {
        _winTimes++
    }
}
<https://github.com/chenyunguiMilook/swift-evolution#impact-on-existing-code>