[swift-evolution] Should closures support inout parameters?

Braeden Profile jhaezhyr12 at gmail.com
Fri Sep 16 21:54:30 CDT 2016


I was writing some code that would allow transformations of values as part of an expression, and I came across a strange error:

/// Returns the operand after a given transformation.
///
/// Example:  `let newRect = myRect << { $0.origin.x += 3 }`
func << <T> (given: T, transformation: (inout T) -> ()) -> T
{
	var result = given
	transformation(&result)
	return result
}

let volume = component.volume << { $0.ranges.z.width = 0 } // Error:  Expression type () is ambiguous without more context.
let volume = component.volume << { $0.ranges.z.width = 0; return () } // Error:  Cannot assign to property: ‘$0’ is immutable.
let volume = component.volume << { (x: inout SCNBoxVolume) in x.ranges.z.width = 0 } // Succeeds!


Obviously, this code could easily create a var for volume and mutate it, but it doesn’t solve my problem.  Am I misunderstanding how this could work?  This is the only overload of << that accepts a closure, and even the code completion recognizes that $0 is a SCNBoxVolume.  It’s just strange that the compiler won’t recognize $0 as an inout parameter off the bat.

Is this a bug, or a design choice?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160916/7c48ede7/attachment.html>


More information about the swift-evolution mailing list