0

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?

3
  • You've allocated a buffer that can store 5 strings, but you haven't actually stored 5 instances in it. The contents are uninitialized, so you're just observing whatever garbage was left in the memory before you had it. The Unsafe in UnsafeMutableBufferPointer isn't coincidental. Commented Jun 16, 2022 at 18:50
  • @Alexander I see, so that's why I can't index it. I'm guessing storeBytes(of:toByteOffset:as:) could be the solution instead of indexing it Commented Jun 16, 2022 at 18:53
  • You can index it (the pointer), it's just that what you'll find at the destination is random junk. What exactly are you trying to achieve with this pointer? You could probably achieve the same thing more easily by just making an regular Array<String> and getting a pointer to the array's buffer. Commented Jun 16, 2022 at 20:39

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

What I did was create an UnsafeMutableBufferPointer<String?> and then umbp.initialize(repeating: nil). Works like a charm. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.