As of SE-0255 developers can omit the return
keyword for single-expression bodied getters for properties, subscripts and single expression bodies functions. This is a nice improvement to the language. Here's an even more improved version of the same proposal.
Existing Syntax for Properties
var location: Location { .init(latitude: lat, longitude: long) }
Proposed Change
var location: Location -> .init(latitude: lat, longitude: long)
Existing Syntax for Functions
extension Sequence where Element == Int {
func sum() -> Element {
reduce(0, +)
}
}
Proposed Change
extension Sequence where Element == Int {
func sum() -> reduce(0, +)
}
The return type of the function is automatically interpolated, which is similar to the type interpolation already available in Swift.
Existing Syntax for Subscripts
struct Echo<T> {
subscript(_ value: T) -> T { value }
}
Proposed Change
With an implicit getter:
struct Echo<T> {
subscript(_ value: T) -> value
}
The return type of the subscript i automatically interpolated, which is similar to the type interpolation already available in Swift.
With an explicit getter and setter:
struct GuaranteedDictionary<Key : Hashable, Value> {
var storage: [Key : Value]
var fallback: Value
subscript(key: Key) -> Value {
get -> storage[key] ?? fallback
set {
storage[key] = newValue
}
}
}
When you look at both existing and proposed change, the braces removed will provide even better readability and the code looks clean.
The proposed change also improves the semantics of the -> symbol for returning values across properties as well, expecially for getters.
The developers can still use existing syntax, if required.