简体   繁体   中英

Can not convert expression's type int to type void swift

I am trying some obj-c code to swift and this is my obj-c code:

NSString *this_device = @"";
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size + 1);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
machine[size] = 0;
NSString *machineString = [NSString stringWithFormat:@"%s", machine];

I converted it into swift code:

 var this_device : NSString = ""
    var size : size_t?
    sysctlbyname("hw.machine", nil, &size!, nil, 0)
    var machine = malloc(size! + 1)
    sysctlbyname("hw.machine", machine, &size!, nil, 0)
    machine[size] = 0 //Can not convert expression's type 'int' to type 'Void'

But I am getting error at machine[size] = 0 .

I don't understand what is wrong here.

malloc return type is Void * , so machine[size] expect a Void type.

you need to use

var machine = UnsafeMutablePointer<CChar>.alloc(size!+1)

to alloc the char* pointer

There are two errors in your code. First (as already noticed by SolaWing), the allocated pointer must be a pointer to CChar (aka Int8 ). This can be done with

var machine = UnsafeMutablePointer<CChar>.alloc(...)

or

var machine = UnsafeMutablePointer<CChar>(malloc(...))

Second , the size variable must not be an optional but a an initialized size_t variable which is passed as inout parameter to sysctlbyname() :

var size = size_t(0)
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = UnsafeMutablePointer<CChar>(malloc(size + 1))
sysctlbyname("hw.machine", machine, &size, nil, 0)
machine[size] = 0
let machineString = String.fromCString(machine)!
free(machine)
println(machineString)

Alternatively, you can create a Swift array instead of allocating memory, this has the advantage that the memory is released automatically:

var size = size_t(0)
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](count: size + 1, repeatedValue: 0)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
machine[size] = 0
let machineString = String.fromCString(machine)!
println(machineString)

The above code compiles with Swift 1.2 (Xcode 6.3 beta). In Swift 1.1 (Xcode <= 6.2), size_t has to be converted to Int at

var machine = [CChar](count: Int(size) + 1, repeatedValue: 0)

machine[Int(size)] = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM