Clashsoft Clashsoft - 3 months ago 33
Swift Question

What is an 'open var' in Swift?

The

file from the standard library contains the following few lines of code around line 228:

extension NSObject : Equatable, Hashable {
/// ...
open var hashValue: Int {
return hash
}
}


My question is: What does
open var
mean in this context? Is this a special keyword / modifier, although it is not mentioned in the Declarations part of the Language Reference, or something else?

Answer

open is a new access modifier in Swift 3, introduced with the implementation of

It is available with the Swift 3 snapshot from August 7, 2016, but not in the default Xcode 8.0 toolchain that comes with Xcode 8 beta 5.

In short:

  • A open class is accessible and subclassable outside of the defining module. A open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

So open is what public used to be in previous Swift releases, and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability:

“open” is now simply “more public than public”, providing a very simple and clean model.

In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses.

For more examples and details, have a look at SE-0117.