Generate random alphanumeric string in Swift

前端 未结 22 847
暖寄归人
暖寄归人 2020-11-27 09:51

How can I generate a random alphanumeric string in Swift?

相关标签:
22条回答
  • 2020-11-27 10:04

    If your random string should be secure-random, use this:

    import Foundation
    import Security
    
    // ...
    
    private static func createAlphaNumericRandomString(length: Int) -> String? {
        // create random numbers from 0 to 63
        // use random numbers as index for accessing characters from the symbols string
        // this limit is chosen because it is close to the number of possible symbols A-Z, a-z, 0-9
        // so the error rate for invalid indices is low
        let randomNumberModulo: UInt8 = 64
    
        // indices greater than the length of the symbols string are invalid
        // invalid indices are skipped
        let symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    
        var alphaNumericRandomString = ""
    
        let maximumIndex = symbols.count - 1
    
        while alphaNumericRandomString.count != length {
            let bytesCount = 1
            var randomByte: UInt8 = 0
    
            guard errSecSuccess == SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomByte) else {
                return nil
            }
    
            let randomIndex = randomByte % randomNumberModulo
    
            // check if index exceeds symbols string length, then skip
            guard randomIndex <= maximumIndex else { continue }
    
            let symbolIndex = symbols.index(symbols.startIndex, offsetBy: Int(randomIndex))
            alphaNumericRandomString.append(symbols[symbolIndex])
        }
    
        return alphaNumericRandomString
    }
    
    0 讨论(0)
  • 2020-11-27 10:05

    My even more Swift-ier implementation of the question:

    func randomAlphanumericString(length: Int) -> String {
    
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".characters
        let lettersLength = UInt32(letters.count)
    
        let randomCharacters = (0..<length).map { i -> String in
            let offset = Int(arc4random_uniform(lettersLength))
            let c = letters[letters.startIndex.advancedBy(offset)]
            return String(c)
        }
    
        return randomCharacters.joinWithSeparator("")
    }
    
    0 讨论(0)
  • 2020-11-27 10:07

    Simple and Fast -- UUID().uuidString

    // Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"

    public var uuidString: String { get }

    https://developer.apple.com/documentation/foundation/uuid

    Swift 3.0

    let randomString = UUID().uuidString //0548CD07-7E2B-412B-AD69-5B2364644433
    print(randomString.replacingOccurrences(of: "-", with: ""))
    //0548CD077E2B412BAD695B2364644433
    

    EDIT

    Please don't confuse with UIDevice.current.identifierForVendor?.uuidString it won't give random values.

    0 讨论(0)
  • 2020-11-27 10:09

    For folks who don't want to type out the entire set of characters:

    func randomAlphanumericString(length: Int) -> String  {
        enum Statics {
            static let scalars = [UnicodeScalar("a").value...UnicodeScalar("z").value,
                                  UnicodeScalar("A").value...UnicodeScalar("Z").value,
                                  UnicodeScalar("0").value...UnicodeScalar("9").value].joined()
    
            static let characters = scalars.map { Character(UnicodeScalar($0)!) }
        }
    
        let result = (0..<length).map { _ in Statics.characters.randomElement()! }
        return String(result)
    }
    
    0 讨论(0)
  • 2020-11-27 10:11

    With Swift 4.2 your best bet is to create a string with the characters you want and then use randomElement to pick each character:

    let length = 32
    let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let randomCharacters = (0..<length).map{_ in characters.randomElement()!}
    let randomString = String(randomCharacters)
    

    I detail more about these changes here.

    0 讨论(0)
  • 2020-11-27 10:12

    Here's a ready-to-use solution in Swiftier syntax. You can simply copy and paste it:

    func randomAlphaNumericString(length: Int) -> String {
        let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let allowedCharsCount = UInt32(allowedChars.characters.count)
        var randomString = ""
    
        for _ in 0 ..< length {
            let randomNum = Int(arc4random_uniform(allowedCharsCount))
            let randomIndex = allowedChars.index(allowedChars.startIndex, offsetBy: randomNum)
            let newCharacter = allowedChars[randomIndex]
            randomString += String(newCharacter)
        }
    
        return randomString
    }
    

    If you prefer a Framework that also has some more handy features then feel free to checkout my project HandySwift. It also includes a beautiful solution for random alphanumeric strings:

    String(randomWithLength: 8, allowedCharactersType: .alphaNumeric) // => "2TgM5sUG"
    
    0 讨论(0)
提交回复
热议问题