0
func hasUniqueDigits(number: String) -> Bool {
    var numbers = [1, 2, 3, 4, 5, 6, 7]
    for i in 1...6 {
        var partOne = number.firstIndex(of: String.Element("\(i)"))
        var partTwo = String(numbers.firstIndex(of: Int(partOne))!)
        numbers.remove(at: partTwo)
    }
    if numbers.count == 1 {
        return true
    } else {
        return false

This is a function for determining whether a six-digit number containing only the digits 1-7 contains all unique digits. Examples: 145327 works, 114723 doesn't because it has two ones, and 183427 doesn't because it contains an 8. I have typed in random !'s to see if it was an optional problem and that didn't work. Can you please let me know hot to fix this error?

  • Does this answer your question? [Removing duplicate elements from an array in Swift](https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift) – Ahmet Sina Ustem Mar 30 '22 at 10:36

1 Answers1

0

Not a direct answer to your question but it would be much easier to use sets. To check if the string have duplicated digits all you need is to check if the string count is the same of the character set count. To check if the string has only the allowed digits you can simply check if the number character set is a subset of the numbers character set:

func hasUniqueDigits(number: String) -> Bool {
    let set1 = Set(number)
    if number.count != set1.count { return false }
    return set1.isStrictSubset(of: Set("1234567"))
}

hasUniqueDigits(number: "145327")  // true
hasUniqueDigits(number: "114723")  // false
hasUniqueDigits(number: "183427")  // false

Note that this would return true for an empty string as well. If you want to make sure this method returns false just add a check to return false if number is empty:

if number.count != set1.count || number.isEmpty { return false }
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571