简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM