UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 :-)

1      

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")
}

1      

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).

1      

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!

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.