I like this idea! It's related to a more general idea I have been thinking about for providing syntactic sugar for anonymous structs. The idea is to use double braces {{ }}
to denote an anonymous struct, a capture list to initialize properties, and support trailing anonymous types similar to how we support trailing closures.
When the protocol only has a single method (or possibly subscript) requirement, the body could be used to fulfill the requirement:
protocol Monoid {
associatedtype Value
var empty: Value
func combine(_ lhs: Value, _ rhs: Value) -> Value
}
extension Sequence {
func fold<M: Monoid>(_ monoid: M) -> Element
where M.Value == Element
}
[1, 2, 3].fold {{ [empty = 0] in $0 + $1 }}
Ideally this could be made to work in cases such as Monoid & Hashable
where memberwise-synthesizable conformances are assumed and the compiler understands that the single requirement being fulfilled is combine
.
In cases where multiple requirements must be implemented manually, the body could also support explicit declarations:
[1, 2, 3].fold {{
typealias Value = Int
var empty: Int { 0 }
func combine(_ lhs: Int, _ rhs: Int) -> Int {
lhs + hrs
}
}}
To provide a concrete real world example applied to SwiftUI:
NavigationLink("Details") {{
VStack {
// details view content
}
}}
I haven't thought much about whether that exact syntax is viable or not, but I think sugar along these lines is very interesting. Declaring a nominal type can be sometimes be inconvenient, especially considering the restriction on declaring them inside a function in generic contexts.