0

I want to be able to compare values from the [String] level instead of the String level. Here's what I mean:

var connectedNames:[[[String]]] = [[[]]]

for var row: Int = 0; row < connectedNames[0].count; row++ {
    if self.connectedNames[0][row] as! String == "asdf" {

    }
}

But the cast here from [String] to String fails so I can't make this value comparison.

So the main problem is this: Is there anyway to compare the String value of a [[String]] to a String? In other words, the String value that I get from indexing connectedNames like so connectedNames[0][0] == "Some String"?

2
  • 1
    Just a suggestion: Perhaps instead of nesting arrays so many levels, you could define a class or struct that does what you are looking to achieve, complete with a method that performs the comparison you're after, get it working, and forget about the implementation details. Your future self will thank you down the line. Commented May 2, 2016 at 1:53
  • @NicolasMiari Thank you for your suggestion. But I am so noob that I don't really know how to use classes and structures effectively. So I have a vague understanding of you meaning. I hope one day, I'll get to see how to use them correctly in other people's code! Commented May 3, 2016 at 10:29

1 Answer 1

2

You can only compare [[String]] to String by using the subscript method of the Array to access the inner element. This would work:

func compare() -> Bool {
    let arr: [[String]] = [["foo"]]
    let str: String = "foo"

    guard let innerArr = arr[0] else {
      return false
    }

    guard let element = innerArr[0] else {
      return false
    }

    return element == str
}
Sign up to request clarification or add additional context in comments.

3 Comments

The triple '===' is to compare of that are the exact same object not if their value is the same
Thank you @ChristopherHarris for your answer! I truly appreciate your help. I am trying to understand it right now. One thing though, why do you have the guard? Is that necessary? Or is it just safer coding?
Better coding. Swift prefers guard over nested conditionals for readability. Please accept this answer too, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.