2016-09-21 223 views
2

我有一個函數返回某些系統值。它在Swift 2.2中運行良好,我剛剛升級到Xcode 8和Swift 3,現在它失敗了。在Swift 3中將NSData轉換爲NSString?

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」。它建立正常,但在運行時,我得到以下錯誤:

Could not cast value of type '__NSCFData' (0x7fff7b833ec0) to 'NSString' (0x7fff7ac32038).

+0

對於其財產,你調用該函數? –

回答

0

請不要註釋類型除非編譯器告訴你這樣做。

例如IOServiceGetMatchingService返回一個非可選io_service_t,您的可選註釋使情況變得更糟。

IORegistryEntryCreateCFProperty返回Unmanaged<CFTypeRef>!不需要註釋以及字符串插值和轉換爲隱式解包可選。

CFTypeRef可以橋接到本機Swift類型。

如果返回類型是(NS)Data它最不可能在以前的版本中工作。

如果後者可以轉換爲String,則此代碼考慮StringData

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 
} 
5

更換

let nsAnswer = (cfAnswer as! NSString) 

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