Swift getaddrinfo
<p>POSIX <code>getaddrinfo</code> allocates memory that must later be freed using <code>freeaddrinfo</code>.
See <a href="http://manpages.ubuntu.com/manpages/xenial/en/man3/getaddrinfo.3.html" rel="nofollow">http://manpages.ubuntu.com/manpages/xenial/en/man3/getaddrinfo.3.html</a></p>

<p>To simplify the API, I've created this function:</p>

<pre><code>import Foundation

enum SystemError: Swift.Error {
    case getaddrinfo(Int32, Int32?)
}

public func getaddrinfo(node: String?, service: String?, hints: addrinfo?) throws -&gt; [addrinfo] {
    var err: Int32
    var res: UnsafeMutablePointer&lt;addrinfo&gt;?
    if var hints = hints {
        err = getaddrinfo(node, service, &amp;hints, &amp;res)
    } else {
        err = getaddrinfo(node, service, nil, &amp;res)
    }
    if err == EAI_SYSTEM {
        throw SystemError.getaddrinfo(err, errno)
    }
    if err != 0 {
        throw SystemError.getaddrinfo(err, nil)
    }
    defer {
        freeaddrinfo(res)
    }
    var result = [addrinfo]()
    var ai = res?.pointee
    while ai != nil {
        result.append(ai!)
        ai = ai!.ai_next?.pointee
    }
    return result
}
</code></pre>

<p>I don't feel that the function is correct, though.</p>

<ul>
<li>How can the Swift memory model know that <code>getaddrinfo</code> allocates memory, and that Swift should not overwrite that memory with own stuff?</li>
<li>How can Swift know that <code>freeaddrinfo</code> deletes the whole list, and that it should copy out ai information that has been assigned to the result array?</li>
</ul>

<p>What's the correct way to interface with <code>getaddrinfo</code>?</p>