0

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

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
Edward Ashak
  • 2,411
  • 2
  • 23
  • 38

2 Answers2

4

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)'

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
0

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)!
}
Halcao
  • 56
  • 1
  • 5