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

SOLVED: Array contains logic not working

Forums > SwiftUI

Greetings,

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"
    print("Failure")
} else {
    host.hostStatus = "Success"
    print("Success")
}

print(host.hostStatus!)

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"
  print("Failure")
} else {
  hostStatus = "Success"
  print("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!

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.