在Swift 3中将NSData转换为NSString?

use*_*833 2 xcode nsstring nsdata swift3

我有一个返回某些系统值的函数.它在Swift 2.2中运行良好,我刚刚升级到Xcode 8和Swift 3,现在它失败了.

func ioPlatExpertDevString(_ property: String) -> String {
    // Start tapping in to the IO Service
    let ioPlatformExpertDevice:io_service_t? = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))

    var sAnswer = "Not Found"
    let cfAnswer:AnyObject! = IORegistryEntryCreateCFProperty(ioPlatformExpertDevice!, "\(property)" as CFString!, kCFAllocatorDefault, 0).takeRetainedValue()
    if (cfAnswer != nil) {
        let nsAnswer = (cfAnswer as! NSString)
        sAnswer = nsAnswer.uppercased
    }

    // Close the IO Service
    IOObjectRelease(ioPlatformExpertDevice!)

    return sAnswer
}
Run Code Online (Sandbox Code Playgroud)

之前,我使用的是"CFData"而不是"AnyObject".它构建良好,但在运行时,我收到以下错误:

无法将类型'__NSCFData'(0x7fff7b833ec0)的值转换为'NSString'(0x7fff7ac32038).

Leo*_*tim 5

更换

let nsAnswer = (cfAnswer as! NSString) 
Run Code Online (Sandbox Code Playgroud)

let nsAnswer = NSString(data: cfAnswer as! Data, encoding: String.Encoding.utf8.rawValue)
Run Code Online (Sandbox Code Playgroud)