Im trying to create a function to retrieve my Mac's RAM usage but I get alerts saying essentially that my 'scanDouble' and 'scanCharecters(from:into:)' methods have been depreciated and Xcode also throw me these alerts if I compile this code. what are the newer alternatives to these methods?
import Foundation
class RAMUsage {
let processInfo = ProcessInfo.processInfo
func getRAM() {
let physicalMemory = processInfo.physicalMemory
let formatter = ByteCountFormatter()
formatter.countStyle = .memory
let formattedMemoryUsage = formatter.string(fromByteCount: Int64(physicalMemory))
parseAndPrint(formattedMemoryUsage: formattedMemoryUsage)
}
func parseAndPrint(formattedMemoryUsage: String) {
print("Formatted RAM usage: \(formattedMemoryUsage)")
if let gigsOfRAM = parseFormattedRAMUsage(formattedUsage: formattedMemoryUsage) {
print("RAM Usage in Gigabytes: \(gigsOfRAM) GB")
} else {
print("Could not retrieve or parse RAM usage")
}
}
func parseFormattedRAMUsage(formattedUsage: String) -> Double? {
let scanner = Scanner(string: formattedUsage)
var value: Double = 0.0
var unit: NSString?
if scanner.scanDouble(&value) {
scanner.scanCharacters(from: .letters, into: &unit)
if let unitString = unit as String?, unitString.lowercased() == "GB" {
print("Parsed RAM Usage: \(value) GB")
return value
} else {
print("could not parse and return value")
}
}
return nil
}
}
Those functions do seem to be deprecated in current macOS versions. It's unclear why the documentation is out of date.
The solution is to use the newer versions of these functions such as scanDouble(representation: .decimal)
. The differ in that they return the scanned value, rather than taking a pointer to memory to store the value. Failure is indicated by a nil result instead of a false return value.