[英]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: 我正在尝试快速一些obj-c代码,这是我的obj-c代码:
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
. 但是我在
machine[size] = 0
时遇到错误。
I don't understand what is wrong here. 我不明白这里出了什么问题。
malloc return type is Void *
, so machine[size] expect a Void type. malloc返回类型为
Void *
,因此machine [size]期望为Void类型。
you need to use 你需要使用
var machine = UnsafeMutablePointer<CChar>.alloc(size!+1)
to alloc the char* pointer 分配char *指针
There are two errors in your code. 您的代码中有两个错误。 First (as already noticed by SolaWing), the allocated pointer must be a pointer to
CChar
(aka Int8
). 首先 (已经由SolaWing注意到),分配的指针必须是指向
CChar
的指针(又名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()
: 其次 ,
size
变量一定不能是可选的,而必须是一个初始化的size_t
变量,该变量将作为inout参数传递给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: 另外,您可以创建一个Swift数组而不是分配内存,这样做的好处是可以自动释放内存:
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). 上面的代码使用Swift 1.2(Xcode 6.3 beta)进行编译。 In Swift 1.1 (Xcode <= 6.2),
size_t
has to be converted to Int
at 在Swift 1.1(Xcode <= 6.2)中,必须将
size_t
转换为Int
var machine = [CChar](count: Int(size) + 1, repeatedValue: 0)
machine[Int(size)] = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.