Ankit Thakur Ankit Thakur - 3 months ago 43
Swift Question

C api migration to Swift 3 in XCode 8 beta 6

I am trying to convert C apis in Swift 3 in XCode 8 beta 6.

int payloadSize = 100
char tempBuffer[payloadSize];
memset(tempBuffer, 7, payloadSize);

// Construct the payload.
NSData *payload = [[NSData alloc] initWithBytes:tempBuffer length:payloadSize];


Till XCode 8 beta 3, it was working fine with Swift as:

let payloadSize = 100
var tempBuffer:[CChar]?
memset(&tempBuffer, 7, Int(payloadSize))

// Construct the ping packet.
let payload:NSData = NSData(bytes: tempBuffer!, length: Int(payloadSize))


But in latest XCode beta release, it is creating crash.

Answer

The issue is on the line var tempBuffer:[CChar]?. That's a declaration of a variable called tempBuffer, whose type is Optional<Array<CChar>>. It does not define that array, however. When you try to memset it, it doesn't work because there is no memory allocated.

Instead of using memset, try this instead:

let payloadSize = 100
let buffer = [UInt8](repeatedValue: 7 count: payloadSize)

let payload = NSData(bytes: buffer, length: buffer.count)