I have a C function in a file with name (Buffer is a C struct)
BufferInit(Buffer *buffer, int32_t size)
As I am moving to Swift, in my Swift class I declare a private var like
var buffer:Buffer?
and in init function I make a call like this
BufferInit(&buffer, 32)
But I get compilation errors, what is the correct way to achieve the same in Swift? I call call the same BufferInit from Objective-C without issues but Swift is messy.
EDIT: Here are details,
typedef struct {
void *buffer;
int32_t length;
int32_t tail;
int32_t head;
} Buffer;
Error is compiler is asking me to unwrap buffer and correct the code as(which I don't think is correct):
BufferInit(&buffer!, 32)
1 Answer 1
Your C function is imported to Swift as
func BufferInit(_ buffer: UnsafeMutablePointer<Buffer>!, _ size: Int32)
and you have to pass the address of a (initialized, nonoptional)
variable of type Buffer
as an inout expression.
Structures imported from C have a default constructor in Swift which
initializes all members to zero, so you can write
var buffer = Buffer()
BufferInit(&buffer, 32)
Buffer
struct?buffer
should be initialized and not an optional.