ios - 有没有更好的方法从字典中读取元素?

标签 ios swift nsdictionary

我正在尝试从 Swift 中的 NSDictionary 读取数据,这是我正在实现的委托(delegate)方法中的一个参数(具体来说,是 advertisementData 参数):

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: NSDictionary!, RSSI: NSNumber!) {}

我尝试过几种不同的化身,但我想出的从这本字典中提取数据元素的唯一方法似乎过于复杂。

例如,要从字典中提取字符串,我必须这样做:

let localNamePre: AnyObject? = advertisementData.objectForKey(CBAdvertisementDataLocalNameKey)
if let localName = localNamePre as? String {
   // do stuff
}

或者对于数组:

let serviceDictPre: AnyObject? = advertisementData.objectForKey(CBAdvertisementDataServiceUUIDsKey)
if let serviceDict = serviceDictPre as? Array<CBUUID> {
   // do stuff            
}

这似乎是一种过于复杂的转换为最终数据类型的方法。有没有更好的方法可以跳过 AnyObject 中间变量来执行此操作?我尝试过的所有其他操作都导致了崩溃,因为我试图解开一个 nil 值。

最佳答案

是的,有一种方法,向 NSDictionary 添加扩展方法,如下所示:

extension NSDictionary {
    func extractObjectForKey<T>(key: String, type: T.Type) -> T? {
        let value: AnyObject? = self.objectForKey(key)
        return value as? T
    }
}

并按如下方式使用(在 Playground 上测试):

var dict = NSMutableDictionary()
dict["int"] = 5
dict["string"] = "Hello"

dict.extractObjectForKey("int", type:Int.self) // Prints {Some 5}
dict.extractObjectForKey("string", type: String.self) // Prints {Some "Hello"}
dict.extractObjectForKey("int", type:String.self) // Prints nil (it's not a string)

关于ios - 有没有更好的方法从字典中读取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491604/

相关文章:

iOS 8 - 视频和声音文件无法从主屏幕网络应用程序播放

ios - 如何访问 UITableView 中每一行的相册

ios - 如何最大限度地减少(内存泄漏)ARKit场景中的应用程序内存点击后退按钮?

objective-c - 将 NSDictionary 写入 NSPasteboard

objective-c - 什么会导致 objectForKey : to return null with a valid string in place?

iphone - 在 epub 阅读器中通过 UIwebview 中的 xhtml 文件显示内容时出现问题

ios - 如何遍历字典?

ios - UITableView 创建空白单元格而不是来自 JSON 的任何值

ios - 当选择 UITableViewCell 时,UIImageView 会更改其位置

ios - 将 NSDictionary 值转换为 NSString