Automatic Mutable Pointer Conversion

Swift does have this feature for function call arguments, implemented with the same logic as inout-to-pointer and array-to-pointer conversions. It doesn't have it for operators, though, which could be useful, or for direct assignments. (You also don't need to repeat the type, but that relies on knowing that there's no initializer to convert between pointers of different types.)

import Foundation

print("""
    line one
    line two
    line three

    """.withCString {
    bytes in
    var bytes = bytes // immutable
    var out = [String]()
    while let nextNewline = // mutable
        strchr(bytes, Int32(UInt8(ascii: "\n"))) {
        out.append(String(data:
            Data(bytes: bytes,
                 count: UnsafePointer(nextNewline)-bytes),
                          encoding: .utf8) ?? "")
        bytes = UnsafePointer(nextNewline) + 1
    }
    return out
})
3 Likes