bdesham bdesham - 1 year ago 205
Swift Question

Using sysctlbyname() from Swift

I’m using the code from this Gist to determine which iOS device (e.g.

) my app is running on:

- (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];
return platform;

The Swift documentation indicates that C data types are well-supported, but it doesn’t say anything about C functions. Is there a pure Swift way to retrieve the machine identifier, or will I have to bridge into Objective-C for this?

Answer Source

You can do the same in Swift (error checking omitted for brevity):

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: Int(size), repeatedValue: 0)
    sysctlbyname("hw.machine", &machine, &size, nil, 0)
    return String.fromCString(machine)!

Update for Swift 3:

func platform() -> String {
    var size = 0
    sysctlbyname("hw.machine", nil, &size, nil, 0)
    var machine = [CChar](repeating: 0,  count: Int(size))
    sysctlbyname("hw.machine", &machine, &size, nil, 0)
    return String(cString: machine)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download