Access custom object property while iterating over dictionary

前端 未结 2 602
醉酒成梦
醉酒成梦 2021-01-29 08:54

I have several objects

Struct object {
   var title:String?
}

var one = object(\"green\")
var two = object(\"black\")
var three = object(\"blue\")
相关标签:
2条回答
  • 2021-01-29 09:45

    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) {
                    // ...
                }
            }
        }
    
    }
    
    0 讨论(0)
  • 2021-01-29 09:45

    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.
        }
    }
    
    0 讨论(0)
提交回复
热议问题