WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Array contains logic not working

Forums > SwiftUI


I'm trying to assign a value based on the presence of a string in an array, and while this string is present, the value assigned is the wrong one. Is there something obvious I'm doing wrong?

Here is the piece of code:

print("\(nwHost): \(hostCurrentStatus)")

if hostCurrentStatus.contains("down") {
    host.hostStatus = "Failure"
} else {
    host.hostStatus = "Success"


And in the debugger, I get these outcomes of the print commands above:

www.google.com: ["443#open", "80#open", "12345#down", "5494#down", "23#down", "22#down", "21#down", "54945#down"] Success Success

As you can see, the array hostCurrentStatus does indeed contain occurrences of "down", but for some reason, it does not find it, and always assign success to it.

Thank you :-)


Well, actually it does because it compares the whole string and not just a part of the string which is what you want. Try

if hostCurrentStatus.contains(where: { $0.contains("down") } ) {
  hostStatus = "Failure"
} else {
  hostStatus = "Success"


It's the difference between the array containing "down" (which it doesn't) versus the members of the array containing "down" within their value (which some do).


It makes sense and I thought it could be something like that, taking the whole content of the string in the array to compare, but I was not able to find if there was a difference in the ways of doing it.

Used your code and works as expected now, thank you very much!


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.