0

I'm trying to figure out how to loop through this usernames array, but am not sure the syntax. I am using swift in xcode

I currently have:

 // Read text file
        if let filepath = NSBundle.mainBundle().pathForResource("barbers", ofType: "txt")
        {
            do
            {
                //let contents = try NSString(contentsOfFile: filepath, usedEncoding: nil) as String;
                //print(contents);
                let text = try NSString(contentsOfFile: filepath, usedEncoding: nil) as String;

                // Create character array & parse
                let usernames = text.characters
                    .split { $0 == "\n" }
                    .map { String($0) }
                    .map { String($0.characters.split(" ")[0]) }

                // Print Users
                print(usernames);

                // Test



            }
            catch
            {
                // Catch error?
            }
        }
        else
        {
            // Print error to console log
            print("Error: Could not find text file - something went wrong");
        }

My question is: How can I loop through my usernames array?

I just dont know the swift syntax

I'm looking for something like

for(int i =0; i < usernames.size(); i ++ )
{
  if(usernames[i] == USER)
  {
    b = true;
    break;
  }
  b = false;
}

UPDATES:

Ok so I've figured out how to loop through but now I'm having troubles

I made a global variable

var abc = "";

I then did

let abc = usernames;

now when I try to do this

// Test
for i in abc.characters
{
    print("abc array contents: " + i);
    if(i == theUser)
    {
        print("Barber");
        barb = true;
        break;
    }
    print("USER " + theUser);
    barb = false;
    print("\n");
}

I get the error

Binary operator '+' cannot be applied to operands of type 'String' and 'Character'

and

Binary operator '==' cannot be applied to operands of type 'Character' and 'String'

9
  • 1
    developer.apple.com/library/ios/documentation/Swift/Conceptual/… that should help Commented Apr 18, 2016 at 19:43
  • kye right now im using this and its not working for some reason... But when i print out the contents of i it says what it should say but its like not even executing the body of my for loop for some reason... here is whati have // Test for i in usernames { print(i); if(i == theUser) { print("Barber"); barb = true; break; } barb = false; } Commented Apr 18, 2016 at 20:01
  • Check out the answers provided, they all should work! Also could you update your question with that code (it's quite hard to read in comments) Commented Apr 18, 2016 at 20:05
  • If you just want to check if the usernames array contains a given string: if usernames.contains(USER) { ... } Commented Apr 18, 2016 at 20:05
  • Check out my updated post. I'm now running into a different problem trying to loop through the array Commented Apr 18, 2016 at 20:30

3 Answers 3

1

All of these above work, but my favorite Swifty for loop is

  for index in 0..< usernames.count { 
     //your code here
     //to get an object at a specific index you call usernames[index]
  }

In response to your updated question I believe you need to cast your character as a string. Something like

  let myCharacterAsAString = String(i)
  print("abc array contents: " + myCharacterAsAString);
  if(myCharacterAsAString == theUser)
  {
    print("Barber");
    barb = true;
    break;
  }
  print("USER " + theUser);
  barb = false;
  print("\n");
}
Sign up to request clarification or add additional context in comments.

7 Comments

How can I compare the strings in the username array to another string or textfield?
// Test for i in usernames { print(i); if(i == theUser) { print("Barber"); barb = true; break; } barb = false; } this isnt working
Something like this if (usernames[index] == inputString) { //do this } else { // do something else }
Check out my updated post. I'm now running into a different problem trying to loop through the array
Your code compiled, but for some reason its not even going into my loops body
|
1
for username in usernames
{
    if(username == USER)
    {
        b = true;
        break;
    }
    b = false;
}

or if you need access to current item's index:

for (index, username) in usernames.enumerate()
{
    // same body as above
}

4 Comments

how can i compare the username to another string ?
how can i also compare username to a textfield? for some reason this isnt working // Test for i in usernames { print(i); if(i == theUser) { print("Barber"); barb = true; break; } barb = false; }
@Yusha comparing to another string is achieved simply by using equality operator (==). Updated the answer. To get text out of textField just access its 'text' property: if(username == someTextField.text) {//... }
Check out my updated post. I'm now running into a different problem trying to loop through the array
0

I believe latest versions of Swift have done away with the C-style for-loop. This might not be super helpful but the way to iterate in Swift would likely be with a for-in loop

for username in usernames
{
    if username == USER
    {
        b = true
        break
    }
    b = false
}

2 Comments

Check out my updated post. I'm now running into a different problem trying to loop through the array
@Yusha in swift you can't append a string to another string with +. in this case you could do print("abc array contents: \(i)") As for your error on the == operator, you should probably compare objects of the same type like char == char. you can probably do if i == theUser.characterAtIndex(0) for your conditional if you're just expecting one character in theUser

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.