[swift-evolution] Proposal: One-past-end array pointers and convertibility of nil for interaction with C APIs

Charles Srstka cocoadev at charlessoft.com
Thu Dec 24 02:57:12 CST 2015


> On Dec 24, 2015, at 1:11 AM, Árpád Goretity <arpad.goretity at gmail.com> wrote:
> 
> > The comments in the generated header for UnsafeMutablePointer claim that its regular init() method constructs a null pointer.
> 
> That's right, and I have tried it as well. Yet, type inference doesn't like like it, and I get back an error similar to what I have already described, but this time with inout and UnsafeMutablePointer:
> 
>     result values in '? :' expression have mismatching types 'inout T' and 'UnsafeMutablePointer<T>'


That’s because you’re putting it in a ternary expression. Swift has magic to automatically turn inout arguments (which is what you get when you put a & in front of an argument) into Unsafe(Mutable)Pointers if that’s what a function asks for. However, you’re not getting to that point, because you’re putting an inout argument and an UnsafeMutablePointer on opposite sides of the ternary operator. That won’t work, because the ternary operator requires both objects to be of the same type, and since your inout argument hasn’t been sent to the function yet, it hasn’t been automagically translated into a pointer.

What Félix said is also true; you can’t trust that &array[0] will get you a pointer to the array’s internal storage. It’s better to use .withUnsafeMutableBufferPointer for that.

Charles

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


More information about the swift-evolution mailing list