Home > Back-end >  pointer arrays to String
pointer arrays to String

Time:06-17

I need to have a pointer array like in C, in Swift.

The following code works:

let ptr = UnsafeMutableBufferPointer<Int32>.allocate(capacity: 5)
ptr[0] = 1
ptr[1] = 5

print(ptr[0], ptr[1]) // outputs 1 5

The following code, however, does not work:

let ptr = UnsafeMutableBufferPointer<String>.allocate(capacity: 5)

print(ptr[0]) // Outputs an empty string (as expected)
print(ptr[1]) // Just exits with exit code 11

When I do print(ptr[1]) in the swift REPL, I get the following output:

Execution interrupted. Enter code to recover and continue.
Enter LLDB commands to investigate (type :help for assistance.)

How can I create a C-like array with Strings (or any other reference type, as this also doesn't seem to work with classes).

What should I adjust?

CodePudding user response:

You need to initialize the memory with valid String data.

let values = ["First", "Last"]
let umbp = UnsafeMutableBufferPointer<String>.allocate(capacity: values.count)
_ = umbp.initialize(from: values)
print(umbp.map { $0 })

umbp[0] = "Joe"
umbp[1] = "Smith"

print(umbp.map { $0 })

Prints:

["First", "Last"]
["Joe", "Smith"]
  • Related