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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.