Access custom object property while iterating over dictionary

╄→尐↘猪︶ㄣ 提交于 2019-12-02 14:09:18

you are iterating over a dictionary by looking at it keys and values.

But the values aren't strings but arrays of strings.

do

import Foundation

struct object {
    var title:String?
}

var one = object(title:"green")
var two = object(title:"black")
var three = object(title:"blue")

var dict = ["a":[one, two], "b":[three]]

for (key, value) in dict {
    for obj in value {
        if let title = obj.title {
            if title.lowercaseString.containsString(searchText.lowercaseString) {
                // ...
            }
        }
    }

}

Your value is an array of object "[object]" but not a string, as defined by your code above:

var dict = ["a":[one, two], "b":[three]]

So you have to process the value as an array of objectto find out what you want.

for (key, value) in dict {
    let found = value.filter({ (anObject: object) -> Bool in
        return anObject.title!.lowercaseString.containsString("b")
    })

    if (found.count > 0) {
        //you find what you want.
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!