create a password with at least one number in swift

To create a password with at least one number in Swift, you can use the following code:

main.swift
func createPassword() -> String {
   let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
   var password = ""
   
   // Add 10 random characters to the password
   for _ in 1...10 {
      let randomIndex = Int(arc4random_uniform(UInt32(allowedChars.characters.count)))
      let randomChar = allowedChars[allowedChars.index(allowedChars.startIndex, offsetBy: randomIndex)]
      password += String(randomChar)
   }

   // Ensure that the password contains at least one number
   if !password.contains(where: {CharacterSet.decimalDigits.contains($0.unicodeScalars.first!)}) {
      // Replace a random character with a number
      let randomIndex = Int(arc4random_uniform(UInt32(password.characters.count)))
      let randomNumber = Int(arc4random_uniform(UInt32(10)))
      let index = password.index(password.startIndex, offsetBy: randomIndex)
      password.replaceSubrange(index...index, with: String(randomNumber))
   }
   return password
}
978 chars
22 lines

In this code, allowedChars contains all of the characters that are allowed in the password. A for loop adds 10 random characters to the password string. Then, the code checks if the password contains at least one number using !password.contains(where: {CharacterSet.decimalDigits.contains($0.unicodeScalars.first!)}). If the password doesn't contain a number, then a random character in the password is replaced with a number. Finally, the function returns the password.

gistlibby LogSnag