我正在尝试编写一个程序,将扫描可用的串行端口并将其显示在弹出菜单中.为什么不能直接从IORegistryEntryCreateCFProperty()函数中获取CFString,并在下一行通过字符串插值将其添加到菜单中?由于某种原因,我的变量声明遇到错误:
@H_404_1@
“NSString is not a subtype of CFString”.
import Foundation import Cocoa import IOKit import IOKit.serial @objc class Serial { init() { } @IBOutlet var serialListPullDown : NSPopUpButton! func refreshSerialList(defaultprompt: String) { let masterPort: mach_port_t = kIOMasterPortDefault let classesToMatch: CFDictionary = IOServiceMatching(kIOSerialBSDServiceValue).takeUnretainedValue() var matchingServices: io_iterator_t = 0 // remove everything from the pull down list serialListPullDown?.removeAllItems() // ask for all the serial ports let kernResult = IOServiceGetMatchingServices(masterPort,classesToMatch,&matchingServices) if kernResult == KERN_SUCCESS { // success while (io_object_t() == IOIteratorNext(matchingServices)) { var serialport = IORegistryEntryCreateCFProperty(io_object_t(),kIOCalloutDeviceKey,kcfAllocatorDefault,0) serialListPullDown?.addItemWithTitle("\(serialport)") } } else { // error } } }
Swift.String和NSString是免费的桥接.
原文链接:https://www.f2er.com/swift/319773.htmlNSString和CFString可以彼此转换,但是您不能直接从Swift String转换为CFString,反之亦然.
按照以下步骤从Core Foundation String转换为Swift字符串:
var cfStr:CFString = "Soon,I'll be a Swift String" var nsTypeString = cfStr as NSString var swiftString:String = nsTypeString
CFTypeRef示例:
var cfStr:CFTypeRef = "Soon,I'll be a Swift String" var nsTypeString = cfStr as NSString var swiftString:String = nsTypeString