[swift-evolution] Two-for-Tuesday: Resettable Properties
Patterson, Jason
jason.patterson at wsj.com
Tue Mar 15 08:49:21 CDT 2016
Hi all,
Recently I noticed how `null_resettable` Objective-C properties were
imported into Swift. To recap, a `null_resettable` property in
Objective-C indicates that the getter returns a nonnull value, while
the setter is nullable:
> @property (nonatomic, nonnull, null_resettable) NSString *name;
>
> foo.name = @"Bar";
> foo.name = nil; // "resets" the property
Currently these are imported as implicitly unwrapped optionals (var
name: String!), which is the same as if they were `null_unspecified`.
I believe this can be improved.
I've drafted a proposal that would improve how these are imported. In
a nutshell, Swift would add an extra "reset" method to the imported
interface which would allow users to explicitly reset the property by
name. (The above example would be imported as `var name: String; func
resetName()`.) This would improve readability and allow the getter to
return a non-optional value.
That proposal is here:
https://github.com/patters/swift-evolution/blob/master/proposals/0000-importing-null_resettable.md
However, I then wondered if this feature of Objective-C would be
advantageous to bring to Swift. The thought there is to allow Swift to
declare a property getter as a non-optional type, while allowing the
setter to take an optional type. While a syntactical change has more
cost to Swift, the benefit may outweigh that.
There were a few ideas here but I ultimately settled on a new `set?`
operator. The proposal then details the usage and ramifications of
such a change. For example, the getter would continue to return `T`
while the type of `newValue` available in the setter becomes a `T?`.
There's a corresponding change to willSet clauses.
That proposal is here:
https://github.com/patters/swift-evolution/blob/master/proposals/0000-resettable-properties.md
I think that both of these solve the problem in two different ways and
submit both for your discussion and consideration.
Thanks!
Jason Patterson
@patters
More information about the swift-evolution
mailing list