将CFString转换为NSString – Swift

前端之家收集整理的这篇文章主要介绍了将CFString转换为NSString – Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个程序,将扫描可用的串行端口并将其显示在弹出菜单中.为什么不能直接从IORegistryEntryCreateCFProperty()函数获取CFString,并在下一行通过字符串插值将其添加菜单中?由于某种原因,我的变量声明遇到错误

“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是免费的桥接.

NSString和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

猜你在找的Swift相关文章