[swift-evolution] Proposal: Extend the &x -> UnsafePointer behavior to work with immutable values

Chris Lattner clattner at apple.com
Wed Dec 16 16:24:28 CST 2015

On Dec 16, 2015, at 11:54 AM, Joe Groff via swift-evolution <swift-evolution at swift.org> wrote:
>> On Dec 16, 2015, at 11:44 AM, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
>> # Introduction
>> Swift allows you to pass a &x ref to a function taking Unsafe[Mutable]Pointer, as long as x is mutable.
>> # Solution
>> Allow for using &x with immutable values if and only if the reference is passed as a parameter to a function expecting UnsafePointer

+1 from me on the feature.

> Seems reasonable. As I mentioned on swift-dev, '&x' in Swift indicates "this call mutates x with inout semantics", not the C sense of "I'm passing a pointer", so doing the conversion without an '&' seems more Swift-ish to me.

I don’t think that "more Swift’ish” is a good enough rationalization here :-)

> The semantics of the implicit const pointer conversion also only allow the C call to treat the parameter as if it were an immutable value operand; any capture of or mutation through the variable is UB.

& is a sigil foisted onto the caller, in order to make the semantics of the function more clear, there is no implementation reason to require it.  I suppose what you’re really claiming is that the caller shouldn’t have to use & here, since no mutation is possible and nothing for the caller to need to think about.

I’m not sure about that. Consider that this is our current behavior:

	func f(a : UnsafePointer<Int>) {}
	var a = 42
	f(&a)  // ok
	f(a)  // error: cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>’

It seems weird to me that we’d change this behavior for var, or make UnsafePointer be inconsistent with UnsafeMutablePointer.  Further, UnsafePointer should *also* accept an array as it currently does, and it would be weird to either take a scalar or an array.


More information about the swift-evolution mailing list