[swift-evolution] [Pitch] Don't require & for UnsafeRawPointer
Anders Kierulf
anders at smartgo.com
Thu Apr 20 14:10:28 CDT 2017
Summary: Currently, only mutable values can be passed to UnsafeRawPointer, except for a special case for arrays. That special case should be generalized, allowing any values to be passed to UnsafeRawPointer without using &.
The following code shows the inconsistency in passing values to UnsafeRawPointer:
var varArray = [Int](repeating: 0, count: 6)
var varTuple = (0, 0, 0, 0, 0, 0)
let letArray = [Int](repeating: 0, count: 6)
let letTuple = (0, 0, 0, 0, 0, 0)
func get(_ pointer: UnsafeRawPointer, at index: Int) -> Int {
let a = pointer.bindMemory(to: Int.self, capacity: 6)
return a[index]
}
// Array can be passed directly, automatically takes address.
_ = get(varArray, at: 2) // okay
_ = get(letArray, at: 2) // okay
// When explicitly taking address, can only pass mutable variables.
_ = get(&varArray, at: 2) // okay, but seems inconsistent
_ = get(&letArray, at: 2) // fails: & not allowed
// Passing tuple instead of array fails.
_ = get(varTuple, at: 2) // fails: wrong type
_ = get(letTuple, at: 2) // fails: wrong type
// Adding & to pass a tuple only works for mutable values. Having to
// pass the address using & means that any methods calling this must
// be mutating, even though they don't mutate.
_ = get(&varTuple, at: 2) // okay, but forces mutating
_ = get(&letTuple, at: 2) // fails: cannot pass immutable value
Passing a value to an UnsafeRawPointer parameter should not require use of &, as that forces all code calling it to be mutating. Having a special case for array also doesn't make sense, as the idea of UnsafeRawPointer is that we're interpreting that memory content as whatever we want. Logged as SR-4649.
Proposal:
- Never require & when passing value to UnsafeRawPointer.
- Always require & when passing value to UnsafeMutableRawPointer.
(Fixed size arrays are still needed, but with this tweak, workarounds can be made to work.)
Anders Kierulf
More information about the swift-evolution
mailing list