Getting CPU type in a Swiftly manner for macOS

Is there a way to get the same results as:

%uname -m
arm64

or

%uname -m
x86_64

natively in swift without having to call a system process?

Answered by OOPer in 672208022

natively in swift without having to call a system process?

I do not know any Swift classes which returns the exact result as uname -m.
One possible way is calling the system function in Swift:
Code Block
var systeminfo = utsname()
uname(&systeminfo)
let machine = withUnsafeBytes(of: &systeminfo.machine) {bufPtr->String in
let data = Data(bufPtr)
if let lastIndex = data.lastIndex(where: {$0 != 0}) {
return String(data: data[0...lastIndex], encoding: .isoLatin1)!
} else {
return String(data: data, encoding: .isoLatin1)!
}
}
print(machine)


Accepted Answer

natively in swift without having to call a system process?

I do not know any Swift classes which returns the exact result as uname -m.
One possible way is calling the system function in Swift:
Code Block
var systeminfo = utsname()
uname(&systeminfo)
let machine = withUnsafeBytes(of: &systeminfo.machine) {bufPtr->String in
let data = Data(bufPtr)
if let lastIndex = data.lastIndex(where: {$0 != 0}) {
return String(data: data[0...lastIndex], encoding: .isoLatin1)!
} else {
return String(data: data, encoding: .isoLatin1)!
}
}
print(machine)


Getting CPU type in a Swiftly manner for macOS
 
 
Q