我正在使用此Gist中的代码来确定iPhone5,1我的应用在哪个iOS设备上运行:
iPhone5,1
- (NSString *)platform { size_t size; sysctlbyname("hw.machine", NULL, &size, NULL, 0); char *machine = malloc(size); sysctlbyname("hw.machine", machine, &size, NULL, 0); NSString *platform = [NSString stringWithUTF8String:machine]; free(machine); return platform; }
Swift文档表明C数据类型得到了很好的支持,但是它并没有说明C函数。是否有一种纯粹的Swift方法来检索机器标识符,还是为此我必须桥接到Objective- C中?
您可以在Swift中执行相同的操作(为简便起见,省略了错误检查):
func platform() -> String { var size : Int = 0 // as Ben Stahl noticed in his answer sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](count: size, repeatedValue: 0) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String.fromCString(machine)! }
Swift 3更新:
func platform() -> String { var size = 0 sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](repeating: 0, count: size) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String(cString: machine) }