指向String的指针数组



我需要有一个指针数组像在C中,在Swift。

下面的代码可以工作:

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

但是,下面的代码不起作用:

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

当我在swift REPL中执行print(ptr[1])时,我得到以下输出:

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

如何使用string(或任何其他引用类型,因为这似乎也不适用于类)创建类似c的数组。

我应该调整什么?

您需要用有效的String数据初始化内存

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 })

打印:

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