Alexey K Alexey K - 4 months ago 16
Swift Question

Access custom object property while iterating over dictionary

I have several objects

Struct object {
var title:String?
}

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


Also I have a dictionary

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


What I want is to iterate over dictionary values and find all objects that starts from "b".

I though about something like

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


but I get an error of

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


how can I deal with this ?

Answer

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

}