在Swift 3中将NSData转换为NSString?

时间:2016-09-21 14:14:22

标签: 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
}

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

  

无法转换类型' __ NSCFData'的值(0x7fff7b833ec0)到' NSString' (0x7fff7ac32038)。

3 个答案:

答案 0 :(得分:5)

<强>替换

let nsAnswer = (cfAnswer as! NSString) 

let nsAnswer = NSString(data: cfAnswer as! Data, encoding: String.Encoding.utf8.rawValue)

答案 1 :(得分:0)

除非编译器告诉您这样做,否则请注释类型。

例如IOServiceGetMatchingService会返回一个非可选的io_service_t,您的可选注释会使其更糟。

IORegistryEntryCreateCFProperty返回Unmanaged<CFTypeRef>!不需要注释,字符串插值和强制解包可选的强制转换。

CFTypeRef可以桥接到本机Swift类型。

如果返回类型为(NS)Data,则它在以前的版本中最不可能使用。

如果后者可以转换为String,则此代码会考虑DataString

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

  var sAnswer = "Not Found"
  let cfAnswer = IORegistryEntryCreateCFProperty(ioPlatformExpertDevice, property as CFString, kCFAllocatorDefault, 0).takeRetainedValue()
  if let cfData = cfAnswer as? Data, let answer = String(data:cfData, encoding:.utf8) {
    sAnswer = answer.uppercased()
  } else if let answer = cfAnswer as? String {
    sAnswer = answer.uppercased()
  }
  // Close the IO Service
  IOObjectRelease(ioPlatformExpertDevice)
  return sAnswer
}

答案 2 :(得分:0)

有关Swift的最新版本:

String(decoding: data, as: UTF8.self)