我正在尝试从 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/