Swift: macのバッテリー温度を取得する

1 min読了の目安(約500字TECH技術記事
import IOKit

func temperature() -> Double {
    let service: io_service_t = IOServiceGetMatchingService(
        kIOMasterPortDefault,
        IOServiceNameMatching("AppleSmartBattery")
    )
    let prop = IORegistryEntryCreateCFProperty(
        service,
        NSString(string: "Temperature") as CFString,
        kCFAllocatorDefault,
        0
    )
    let _ = IOObjectRelease(service)
    guard let value = prop?.takeUnretainedValue(),
          let temp = value as? Double
    else { return 0.0 }
    return temp / 100.0
}

Swift.print(temperature())