在Swift和iOS Support> = 8.0中使用空字符串过滤NSDictionary

时间:2016-02-05 12:09:23

标签: ios swift dictionary ios8

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

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。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

因为上面的dict是常量,所以在Dictionary扩展中添加一个额外的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)

答案 1 :(得分:0)

这个解决方案也可行;但艾伦的解决方案更精确。

public class CustomAdapter extends ArrayAdapter<MyObject> {

private List<MyObject> list = new ArrayList<MyObject>();

public CustomAdapter(Context context, int resource) {
    super(context, resource);
}

 @Override
 public void add(MyObject obj) {
     this.list.add(obj);
     super.add(obj);
 }

 @Override
 public void remove(MyObject obj) {
     int i = getPosition(obj);
     if(i >= 0)
         list.remove(i);
     super.remove(obj);
 }

 @Override
 public void clear() {
     this.list.clear();
     super.clear();
 }

 @Override
 public MyObject getItem(int position) {
     return this.list.get(position);
 }

 @Override
 public int getPosition(MyObject obj) {
     for(int i = 0; i < list.size(); i++) {
         if(list.get(i).equals(obj))
             return i;
     }
     return -1;
 }}