迭代字典时访问自定义对象属性

时间:2016-07-18 14:59:14

标签: swift

我有几个对象

Struct object {
   var title:String?
}

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

我还有一本字典

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

我想要的是迭代字典值并找到从" b"开始的所有对象。

我虽然喜欢

for (key, value) in dict { 
  if value.lowercaseString.containsString(searchText.lowercaseString)
}

但我收到错误

value of type [object] has no member 'lowercaseString'

我该如何处理?

2 个答案:

答案 0 :(得分:1)

通过查看字典和值来迭代字典。

但是值不是字符串而是字符串数组。

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) {
                // ...
            }
        }
    }

}

答案 1 :(得分:0)

你的value是一个对象数组" [object]"但不是由上面的代码定义的字符串:

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

因此,您必须将值作为object数组处理,以找出您想要的内容。

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.
    }
}