如何制作更好地访问数组的快速代码?
Posted
技术标签:
【中文标题】如何制作更好地访问数组的快速代码?【英文标题】:How can I make swift code that accesses arrays better? 【发布时间】:2019-12-02 15:40:21 【问题描述】:我有以下代码
if let unwrappedDict = snapshot.value as? NSDictionary
for (index, dd) in unwrappedDict
let dd = dd as? NSDictionary ?? [:]
id = dd["id"] as? String ?? ""
let ccode = dd["code"] as? String ?? ""
if (ccode == code)
if id.count > 0
found = true;
我怎样才能使这段代码更好?我是在专门谈论这一行 let dd = dd as? NS词典?? [:]?
【问题讨论】:
不要在Swift
中使用NS*
类。请改用Swift
类型。使用Swift
Dictionary,您将能够一次检查两个级别。
我刚刚注意到您在标题中谈论数组,但您的代码中没有数组。我错过了什么吗?
您需要发布其余代码。什么是snapshot
,为什么要快速使用 NSDictionary?太多未知数,无法尝试优化您的代码。
那是 Firestore snapshot
?
【参考方案1】:
您可以通过执行以下操作使代码更紧凑、更类似于 Swift 和功能:
let found = (snapshotValue as? NSDictionary)?.compactMap $1 as? NSDictionary .contains $0["code"] as? String == ccode && ($0["id"] as? String)?.isEmpty == false ?? false
逐条解释:
(snapshotValue as? NSDictionary)?.compactMap $1 as? NSDictionary // This tries to cast snapshotValue as an NSDictionary, and only if that succeeds, takes the array of (key, value)'s from the dictionary and tries to cast each value as an NSDictionary. The output of this segment is an array of only values that succeeded in being cast to NSDictionary.
.contains $0["code"] as? String == ccode && ($0["id"] as? String)?.isEmpty == false // In the array of NSDictionary values that are also NSDictionaries themselves, check if any of those child dictionaries meet the condition of having the right code and a non-empty id string. If any one of them do, return true and early exit the loop
?? false // If the original conditional cast of snapshotValue as? NSDictionary fails, return false for the value found
【讨论】:
以上是关于如何制作更好地访问数组的快速代码?的主要内容,如果未能解决你的问题,请参考以下文章