[swift-evolution] Proposal: [stdlib] Remove withUnsafe[Mutable]Pointer[s]()
Kevin Ballard
kevin at sb.org
Wed Dec 16 13:38:25 CST 2015
# Introduction
The stdlib provides functions withUnsafePointer() and withUnsafeMutablePointer() (and plural variants) that take an inout reference and call a block with the UnsafePointer/UnsafeMutablePointer created from the reference.
# Problem
withUnsafePointer() can only be used with mutable variables, because those are the only things that can be used with inout &refs. Both functions are also fairly useless, as &x refs can be passed directly to functions taking an UnsafePointer or UnsafeMutablePointer. The existence of the functions mostly just causes people to think they're necessary when they're not. The provide no functionality that passing &x refs directly to the functions taking a pointer doesn't already fulfill.
# Solution
Remove the functions from the stdlib. The Swift Book should also be updated to talk about passing an &x ref to a function that takes an UnsafePointer or UnsafeMutablePointer (but of course changes to the book are not covered by the open-source project). Most uses of these functions can probably be replaced with a &x ref directly. If any can't, they could be replaced with the following equivalent expressions:
{ (ptr: UnsafePointer<Int>) in
// ...
}(&x)
or:
withExtendedLifetime(&x) { (ptr: UnsafePointer<Int>) in
// ...
}
# Detailed Solution
The functions would be marked as unavailable with a message saying to pass &x directly to the function taking a pointer. If it's feasible to do so, Fix-Its would be introduced for the trivial case of the pointer being used once in the closure as a parameter to a function.
The documentation of UnsafePointer and UnsafeMutablePointer would be edited to include a mention of how &x refs can be passed to functions expecting an UnsafePointer or UnsafeMutablePointer. This way anyone new to the language who encounters those types in the wild will be able to easily see how to create one from a variable.
More information about the swift-evolution
mailing list