0
votes

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

2
"Not sure how to fix it" – Did you read the comment in the second line ? - Martin R
Btw., this is where the code seems to come from: stackoverflow.com/questions/25467082/… - Martin R

2 Answers

4
votes

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

0
votes

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)!
}