1

I have this code:

[
  {
    "id": 176,
    "aSegments": [
      "CUT_SPECIALITIES1", 
      "CUT_SPECIALITIES2", 
      "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 72,
    "prepOven": "15 min / 220C"
  }
]

let searchString = "CUT_SPECIALITIES2"
let products = DataMgr.instance.getProducts(reload: false)
var productsObjectArray = products.filter({
   return  (($0.aSegments?.filter({
       $0.description.lowercased().contains(searchString.lowercased())
   }))?.count)! > 0
})

How can I search CUT_SPECIALITIES2 to find the searched string?

11
  • 1
    Try to format you question, please. It's really hard to read the spaghetti in last line :( Commented Jul 19, 2018 at 6:45
  • You mean how can you search aSegments for CUT_SPECIALITIES2 don't you? Commented Jul 19, 2018 at 6:47
  • 1
    i have parser json in this line: let products = DataMgr.instance.getProducts(reload: false). When I have this code: var productsObjectArray = $0. prepOven?.lowercased().contains(searchString.lowercased()))! - work's fine Commented Jul 19, 2018 at 6:49
  • 1
    What type is products? I mean what does the array contain? Commented Jul 19, 2018 at 6:52
  • 1
    I recommend watching this WWDC 2017 video. Commented Jul 19, 2018 at 6:54

1 Answer 1

2

This is the array I assumed you have :

let array = [
[
    "id" : 176,
    "aSegments": [
    "CUT_SPECIALITIES1",
    "CUT_SPECIALITIES2",
    "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 72,
    "prepOven": "15 min / 220C"
    ],
[
    "id" : 177,
    "aSegments": [
        "CUT_SPECIALITIES1",
        "CUT_SPECIALITIES2",
        "CUT_SPECIALITIE2S"
    ],
    "sunFl": true,
    "inPi": false,
    "noBox": 73,
    "prepOven": "18 min / 120C"
    ]
]

And from this Array of Dictionaries, you want to filter the dictionaries based on the searchString.

let searchString = "CUT_SPECIALITIES2"
let filteredArray = array.filter { (singleProduct) -> Bool in
    guard let aSegments = singleProduct["aSegments"] as? [String] else {
       return false
    }
    return (aSegments.filter({ $0 == searchString }).count > 0)
}

This gives an Array of Dictionaries which contains your searched string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.