Sunday, March 20, 2016

Gathering System Information in Swift With sysctl

Matt Gallagher:

The reason why sysctl feels so cumbersome in Swift is:

  • Creating an array of Int32 and passing that by pointer for the first parameter is a nuisance in Swift
  • You basically need to call sysctl twice: once with oldp equal to nil to get the size required for the result buffer and then a second time with a properly allocated buffer.
  • The result is returned as an untyped buffer of bytes which you then need to interpret correctly.
  • There are a few different ways in which failure can occur and we want to reduce these different ways to idiomatic Swift errors or preconditions.

For these reasons, I use a wrapper around sysctl[…]

1 Comment RSS · Twitter

"The reason why sysctl feels so cumbersome in Swift is:"

Let's sum it up to: calling C APIs from Swift can be worse than using the bridge APIs between Cocoa and CoreFoundation "objects".

One of the reasons why I'm wondering whether Swift has any future as a language to be used for system command line tools (since, AFAIK, the Posix APIs are C-based).

Leave a Comment