Home > Mobile >  Searching for a String in Array<Any>
Searching for a String in Array<Any>

Time:11-04

I'm pretty new to Swift. I have a DB connection to my app and all of the query results are stored in an Array of type Any as I've created one function to pass any queries.

I am now looking to search into this array for a specific string (here for example the email).

let Array = [1, Doe, John, [email protected], jdoe, t, 03/11/2022 15:00:00, nil, 1]

let stringToSearch:String = "[email protected]"

if contains(itemsArray, stringToSearch) {
    NSLog("Term Exists")
}
else {
    NSLog("Can't find term")
}

I've looked at several options, but my main issue is how to move out from Array<Any> to String.

CodePudding user response:

Your first line is total nonsense; no such array can ever be formed. But let's pretend you mean this:

let array = [1, "Doe", "John", "[email protected]", "jdoe", "t", "03/11/2022 15:00:00", nil, 1]

Then you can say

let stringMembersOfArray = array.compactMap { $0 as? String }

And now you have just the strings, and can see what that contains.

CodePudding user response:

You can filter the [Any] array to get just the values with a type of String.

let record: [Any] = ... // the record with lots of values of different types in it
let strings = record.compactMap { $0 as? String }
if let strings.contains(stringToSearch) {
    // found
} else {
    // not found
}

BTW - do not name a variable Array. That's confusing with the Array type. Plus, variable names should begin with lowercase letters.

  • Related