gpt4 book ai didi

ios - 在 Swift 和 iOS 支持中使用空字符串过滤 NSDictionary >= 8.0

转载 作者:行者123 更新时间:2023-11-29 01:15:38 25 4
gpt4 key购买 nike

我有一个字典,其中包含某些值是空字符串的方式。

let fbPostDic: [String: AnyObject] = [
"title":"",
"first_name”:”Ali“,
"last_name”:”Ahmad“,
"nick_name”:”ahmad”,
"gender":1,
"gender_visibility":2,
"dob":"1985-08-25",
"dob_visibility":2,
"city":"Lahore",
"city_visibility":2,
"bio”:”Its bio detail.”,
"bio_visibility":2,
"nationality":"Pakistan",
"nationality_visibility":2,
"relationship_status”:”Single”,
"rel_status_visibility":2,
"relation_with":"",
"relation_with_visibility":2,
"social_media_source":"Facebook",
]

我想过滤这个字典,使新字典只包含没有空字符串的元素。

let fbPostDic: [String: AnyObject] = [
"first_name”:”Ali“,
"last_name”:”Ahmad“,
"nick_name”:”ahmad”,
"gender":1,
"gender_visibility":2,
"dob":"1985-08-25",
"dob_visibility":2,
"city":"Lahore",
"city_visibility":2,
"bio”:”Its bio detail.”,
"bio_visibility":2,
"nationality":"Pakistan",
"nationality_visibility":2,
"relationship_status”:”Single”,
"rel_status_visibility":2,
"relation_with_visibility":2,
"social_media_source":"Facebook",
]

目前的方法有

let keysToRemove = dict.keys.array.filter { dict[$0]! == nil }

但支持iOS9.0以上版本。我也想支持iOS8.0。

有什么建议吗?

最佳答案

由于上面的dict是一个常量,在Dictionary extension中增加一个额外的init方法可以简化这个过程:

extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
init(_ elements: [Element]){
self.init()
for (key, value) in elements {
self[key] = value
}
}
}
print(Dictionary(dict.filter { $1 as? String != "" }))

但是,如果上面的dict可以声明为一个变量。可能在没有上面额外的词典扩展的情况下尝试下面的一个:

var dict: [String : AnyObject] = [...]
dict.forEach { if $1 as? String == "" { dict.removeValueForKey($0) } }
print(dict)

关于ios - 在 Swift 和 iOS 支持中使用空字符串过滤 NSDictionary >= 8.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com