Edward Ashak
Edward Ashak

Reputation: 2421

sysctlbyname failing in swift 1.2

I had this code working in swift 1.1 Not sure how to fix it

var deviceModelIdentifier: String {
    var size : UInt = 0 // Swift 1.2: var size : Int = 0 (as Ben Stahl noticed in his answer)
    //sysctlbyname(_: UnsafePointer<Int8>, _: UnsafeMutablePointer<Void>, _: UnsafeMutablePointer<Int>, _: UnsafeMutablePointer<Void>, _: Int)
    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)!
}

error: cannot invoke 'sysctlbyname' with an argument list of type '(String, nil, inout UInt, nil, Int)' sysctlbyname("hw.machine", nil, &size, nil, 0) ^ error: cannot invoke 'sysctlbyname' with an argument list of type '(String, inout [(CChar)], inout UInt, nil, Int)' sysctlbyname("hw.machine", &machine, &size, nil, 0)

Any help is appreciated

Upvotes: 0

Views: 813

Answers (2)

Halcao
Halcao

Reputation: 56

The Swift 4.0 version

var deviceModel: String {
    var size : Int = 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, encoding: .utf8)!
}

Upvotes: 0

Airspeed Velocity
Airspeed Velocity

Reputation: 40963

The solution is there in the comment in your code: Size is now Int rather than Uint in 1.2, so this compiles:

var deviceModelIdentifier: String {
    var size : Int = 0
    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)!
}

(you can also write var size : size_t = 0 if you prefer)

Error message hints at this when you wade through the unsafe pointer boiler plate:

note: expected an argument list of type '(UnsafePointer< Int8 >, UnsafeMutablePointer< Void >, UnsafeMutablePointer<Int>, UnsafeMutablePointer< Void >, Int)'

Upvotes: 4

Related Questions