-4

I am trying to find the first repeating character in swift, and returning the character found. I am getting a bunch of errors with this code, I am not sure why this is not working.

var myArry = "Hello, World"
var counts = [Character]()

func findRepeating(myArry: String) -> Character
{
    counts = []
    for char in myArry.characters
    {
        if char in counts
        {
            print("Character found")
            return char
        }
        else
        {
            counts.append(char)
        }
    }
    return "A"
}
Frank Boccia
  • 81
  • 1
  • 10
  • 2
    What is `var counts = {}` supposed to do? Please see the Swift book to learn about arrays and how to initialize them. – rmaddy Nov 08 '17 at 05:42
  • @rmaddy Dictionary to store characters found – Frank Boccia Nov 08 '17 at 05:43
  • Then read the Swift book to learn about dictionaries. – rmaddy Nov 08 '17 at 05:43
  • @FrankBoccia You need to initialize a dictionary like `[:]` this. Not like `{}`. And also your'e returning nil to the function which is supposed to return `Character`. – Dayanithi Natarajan Nov 08 '17 at 05:48
  • @FrankBoccia: First Google hit for "Swift How to check if an element is in an array": https://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array. – Martin R Nov 08 '17 at 06:24

1 Answers1

-1

Most simple answer:

let str = "abcdefghijkhlmnop"
var count = 0
for char in str.characters {
    for charNext in str.characters {
        if (char == charNext) {
            count += 1
            if (count > 1) {
                return char           // h
            } 
        }
    }
    count = 0
}
Rishabh
  • 465
  • 5
  • 14