swiftcastingdowncastcfstring

Avoiding forced downcast from Any to CFString


So here's some code I found from another question, it has a forced downcast from Any to CFString

import SystemConfiguration.CaptiveNetwork

func fetchSSIDInfo() -> String? {
    var ssid: String?
    if let interfaces = CNCopySupportedInterfaces() as NSArray? {
        for interface in interfaces {
            // is there any way to remove the force downcast below 👇
            if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                break
            }
        }
    }
    return ssid
}

Do you have to use the forced downcast or is there another way? Are there special rules when dealing with old Corefoundation objects? Because working with NSObjects seems a lot simpler.


Solution

  • Import Foundation to give the compiler information about bridging between Core Foundation types and Foundation types. Then cast the array as you want:

    import Foundation
    import SystemConfiguration.CaptiveNetwork
    
    func fetchSSIDInfo() -> String? {
        var ssid: String?
        if let interfaces = CNCopySupportedInterfaces() as? [CFString] {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface) as NSDictionary? {
                    ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                    break
                }
            }
        }
        return ssid
    }