从 String 到 UnsafePointer<Int8> 的最佳转换是什么?

What is the best conversion from String into UnsafePointer<Int8>?

为了将 String 转换为 UnsafePointer,我使用了这个:

var tail = ("" as NSString).utf8String

但是有没有不用 NSString 强制转换的方法呢?

我在 C-library 方法中使用 UnsafePointer

有专门的方法:.withCString(_:):

yourString.withCString { pointer in
    // work with the pointer
    return result
}

或者,如果您想要 属性,那么 .utf8CString:

var tail = "".utf8CString // ContiguousArray<CChar> (aka ContiguousArray<Int8>)
// and then
tail.withUnsafeBufferPointer { pointer in
    // work with the pointer
    return result
}