在Swift中生成随机的字母数字字符串

时间:2022-11-24 21:59:51

How to generate a random alphanumeric string in Swift?

如何在Swift中生成一个随机的字母数字字符串?

19 个解决方案

#1


205  

func randomStringWithLength (len : Int) -> NSString {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

    var randomString : NSMutableString = NSMutableString(capacity: len)

    for (var i=0; i < len; i++){
        var length = UInt32 (letters.length)
        var rand = arc4random_uniform(length)
        randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
    }

    return randomString
}

Swift 3.0 Update

斯威夫特3.0更新

func randomString(length: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let len = UInt32(letters.length)

    var randomString = ""

    for _ in 0 ..< length {
        let rand = arc4random_uniform(len)
        var nextChar = letters.character(at: Int(rand))
        randomString += NSString(characters: &nextChar, length: 1) as String
    }

    return randomString
}

#2


51  

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:

如果您喜欢的框架也有一些更方便的特性,那么请随意查看我的项目HandySwift。它还包含了一个漂亮的随机字母数字字符串解决方案:

String(randomWithLength: 8, allowedCharactersType: .alphaNumeric) // => "2TgM5sUG"

#3


39  

You may use it also in the following way:

你也可以用以下方式使用:

extension String {

    static func random(length: Int = 20) -> String {

        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {

            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.startIndex.advancedBy(Int(randomValue))])"
        }

        return randomString
    }
}

Simple usage:

简单的用法:

let randomString = String.random()

Swift 3 Syntax:

斯威夫特3语法:

extension String {

    static func random(length: Int = 20) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
        }
        return randomString
    }
}

Swift 4 Syntax:

斯威夫特4语法:

extension String {

    static func random(length: Int = 20) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.count))
            randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
        }
        return randomString
    }
}

#4


13  

Swift:

迅速:

let randomString = NSUUID().uuidString

#5


6  

Swift 2.2 Version

斯威夫特2.2版本

// based on https://gist.github.com/samuel-mellert/20b3c99dec168255a046
// which is based on https://gist.github.com/szhernovoy/276e69eb90a0de84dd90
// Updated to work on Swift 2.2

func randomString(length: Int) -> String {
    let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let charactersArray : [Character] = Array(charactersString.characters)

    var string = ""
    for _ in 0..<length {
        string.append(charactersArray[Int(arc4random()) % charactersArray.count])
    }

    return string
}

Basically call this method that will generate a random string the length of the integer handed to the function. To change the possible characters just edit the charactersString string. Supports unicode characters too.

基本调用这个方法,它将生成一个随机字符串,它的长度是传递给函数的整数。要更改可能的字符,只需编辑字符字符串。支持unicode字符。

https://gist.github.com/gingofthesouth/54bea667b28a815b2fe33a4da986e327

https://gist.github.com/gingofthesouth/54bea667b28a815b2fe33a4da986e327

#6


5  

for Swift 3.0

斯威夫特3.0

func randomString(_ length: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let len = UInt32(letters.length)

    var randomString = ""

    for _ in 0 ..< length {
        let rand = arc4random_uniform(len)
        var nextChar = letters.character(at: Int(rand))
        randomString += NSString(characters: &nextChar, length: 1) as String
    }

    return randomString
}

#7


5  

Simple and Fast -- UUID().uuidString

简单而快速——UUID().uuidString

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

//返回从UUID创建的字符串,例如“E621E1F8-C36C-495A-93FC-0C247A3E6E5F”

public var uuidString: String { get }

public var uuidString: String {get}

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

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

Swift 3.0

斯威夫特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.

请不要与UIDevice.current.identifierForVendor混淆?uuidString它不会给出随机值。

#8


3  

func randomString(length: Int) -> String {
    // whatever letters you want to possibly appear in the output (unicode handled properly by Swift)
    let letters = "abcABC012你好吗????????????∆????∌⌘"
    let n = UInt32(letters.characters.count)
    var out = ""
    for _ in 0..<length {
        let index = letters.startIndex.advancedBy(Int(arc4random_uniform(n)))
        out.append(letters[index])
    }
    return out
}

#9


3  

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("")
}

#10


3  

Might save someone some typing, if you have the unusual case that

如果你有这种不寻常的情况,可能会给别人省点打字的钱

performance matters.

Here's an extremely simple, clear, self-contained function that caches,

这里有一个非常简单,清晰,自包含的函数,

(I think it's the sort of thing you'd just leave at global scope for simplicity.)

(我认为这是你在全球范围内为简约而做的事情。)

func randomNameString(length: Int = 7)->String{

    enum s {
        static let c = Array("abcdefghjklmnpqrstuvwxyz12345789".characters)
        static let k = UInt32(c.count)
    }

    var result = [Character](repeating: "a", count: length)

    for i in 0..<length {
        let r = Int(arc4random_uniform(s.k))
        result[i] = s.c[r]
    }

    return String(result)
}

Note that the point here is this is for a fixed, known character set - it's cached.

注意,这里的重点是这是一个固定的、已知的字符集——它被缓存。

If you need another different character set, just make another cached function,

如果您需要另一个不同的字符集,只需创建另一个缓存的函数,

func randomVowelsString(length: Int = 20)->String{
    enum s {
        static let c = Array("AEIOU".characters)
        ...

Handy tip:

方便的提示:

Note that the set "abcdefghjklmnpqrstuvwxyz12345789" avoids 'bad' characters

There is no 0, o, O, i, etc ... the characters humans often confuse.

没有0 o o i等等…人类经常混淆的角色。

This is often done for booking codes, etc.

这通常用于预订代码等。

#11


2  

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
}

#12


2  

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:

使用Swift 4.2,你最好的办法是创建一个带有你想要的字符的字符串,然后使用randomElement来选择每个字符:

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.

我在这里详细介绍了这些变化。

#13


1  

The problem with responses to "I need random strings" questions (in whatever language) is practically every solution uses a flawed primary specification of string length. The questions themselves rarely reveal why the random strings are needed, but I would challenge you rarely need random strings of length, say 8. What you invariably need is some number of unique strings, for example, to use as identifiers for some purpose.

回答“我需要随机字符串”问题(用任何语言)的问题实际上是每个解决方案都使用了一个有缺陷的主要字符串长度规范。这些问题本身很少揭示为什么需要随机字符串,但我想要挑战的是很少需要随机长度的字符串,比如8。您总是需要一些惟一的字符串,例如,作为某些用途的标识符。

There are two leading ways to get strictly unique strings: deterministically (which is not random) and store/compare (which is onerous). What do we do? We give up the ghost. We go with probabilistic uniqueness instead. That is, we accept that there is some (however small) risk that our strings won't be unique. This is where understanding collision probability and entropy are helpful.

有两种方法可以获得严格唯一的字符串:决定性的(非随机的)和存储/比较(繁重的)。我们做什么呢?我们放弃鬼魂。我们采用概率唯一性。也就是说,我们承认有一些(无论多么小的)风险,我们的字符串不会是唯一的。这就是理解碰撞概率和熵的意义所在。

So I'll rephrase the invariable need as needing some number of strings with a small risk of repeat. As a concrete example, let's say you want to generate a potential of 5 million IDs. You don't want to store and compare each new string, and you want them to be random, so you accept some risk of repeat. As example, let's say a risk of less than 1 in a trillion chance of repeat. So what length of string do you need? Well, that question is underspecified as it depends on the characters used. But more importantly, it's misguided. What you need is a specification of the entropy of the strings, not their length. Entropy can be directly related to the probability of a repeat in some number of strings. String length can't.

因此,我将把不变需求重新表述为需要一些字符串,但重复的风险很小。作为一个具体的例子,假设您希望生成500万个id。你不希望存储和比较每个新字符串,你希望它们是随机的,所以你接受重复的风险。举个例子,假设重复的风险小于1万亿次。那么你需要什么长度的字符串呢?这个问题没有得到充分的说明,因为它取决于所使用的字符。但更重要的是,它被误导了。你需要的是弦的熵,而不是它们的长度。熵可以直接与一些弦重复的概率有关。字符串长度不能。

And this is where a library like EntropyString can help. To generate random IDs that have less than 1 in a trillion chance of repeat in 5 million strings using EntropyString:

这就是像EntropyString这样的库所能提供的帮助。使用EntropyString,生成在500万个字符串中重复的概率小于一万亿分之一的随机id:

import EntropyString

let random = Random()
let bits = Entropy.bits(for: 5.0e6, risk: 1.0e12)
random.string(bits: bits)

"Rrrj6pN4d6GBrFLH4"

“Rrrj6pN4d6GBrFLH4”

EntropyString uses a character set with 32 characters by default. There are other predefined characters sets, and you can specify your own characters as well. For example, generating IDs with the same entropy as above but using hex characters:

EntropyString使用一个默认设置为32个字符的字符集。还有其他预定义的字符集,您也可以指定自己的字符。例如,生成与上面相同的熵的id,但使用十六进制字符:

import EntropyString

let random = Random(.charSet16)
let bits = Entropy.bits(for: 5.0e6, risk: 1.0e12)
random.string(bits: bits)

"135fe71aec7a80c02dce5"

“135 fe71aec7a80c02dce5”

Note the difference in string length due to the difference in total number of characters in the character set used. The risk of repeat in the specified number of potential strings is the same. The string lengths are not. And best of all, the risk of repeat and the potential number of strings is explicit. No more guessing with string length.

注意字符串长度的差异,这是由于所使用的字符集中字符总数的差异造成的。在指定的潜在字符串数量中重复的风险是相同的。字符串长度不是。最重要的是,重复的风险和字符串的潜在数量是明确的。不再猜测字符串长度。

#14


0  

If you just need a unique identifier, UUID().uuidString may serve your purposes.

如果只需要唯一标识符UUID()。uuidString可能符合您的目的。

#15


0  

This is the Swift-est solution I could come up with. Swift 3.0

这是我能想到的最快的解决办法。斯威夫特3.0

extension String {
    static func random(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let randomLength = UInt32(letters.characters.count)

        let randomString: String = (0 ..< length).reduce(String()) { accum, _ in
            let randomOffset = arc4random_uniform(randomLength)
            let randomIndex = letters.index(letters.startIndex, offsetBy: Int(randomOffset))
            return accum.appending(String(letters[randomIndex]))
        }

        return randomString
    } 
}

#16


0  

A pure Swift random String from any CharacterSet.

任何字符集的一个纯快速随机字符串。

Usage: CharacterSet.alphanumerics.randomString(length: 100)

用法:CharacterSet.alphanumerics。randomString(长度:100)

extension CharacterSet {
    /// extracting characters
    public func allCharacters() -> [Character] {
        var allCharacters = [Character]()
        for plane: UInt8 in 0 ... 16 where hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), contains(uniChar) {
                    allCharacters.append(Character(uniChar))
                }
            }
        }
        return allCharacters
    }

    /// building random string of desired length
    public func randomString(length: Int) -> String {
        let charArray = allCharacters()
        let charArrayCount = UInt32(charArray.count)
        var randomString = ""
        for _ in 0 ..< length {
            randomString += String(charArray[Int(arc4random_uniform(charArrayCount))])
        }
        return randomString
    }
}

The allCharacters() is based on Martin R answer.

allCharacters()基于Martin R的回答。

#17


0  

Swift :

迅速:

Just simplified for understandable way in swift.

只是简化了,以理解的方式迅速。

func randomString(_ length: Int) -> String {

    let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
    var randomString = ""

    for _ in 1...length{

        let random = arc4random_uniform(UInt32(master.count))
        randomString.append(String(master[Int(random)]))
    }
    return randomString
}

#18


0  

Updated for Swift 4. Use a lazy stored variable on the class extension. This only gets computed once.

更新迅速4。在类扩展中使用惰性存储变量。这个只计算一次。

extension String {

    static var chars: [Character] = {
        return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".map({$0})
    }()

    static func random(length: Int) -> String {
        var partial: [Character] = []

        for _ in 0..<length {
            let rand = Int(arc4random_uniform(UInt32(chars.count)))
            partial.append(chars[rand])
        }

        return String(partial)
    }
}

String.random(length: 10) //STQp9JQxoq

#19


-1  

func randomUIDString(_ wlength: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var randomString = ""

    for _ in 0 ..< wlength {
        let length = UInt32 (letters.length)
        let rand = arc4random_uniform(length)
        randomString = randomString.appendingFormat("%C", letters.character(at: Int(rand)));
    }

    return randomString
}

#1


205  

func randomStringWithLength (len : Int) -> NSString {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

    var randomString : NSMutableString = NSMutableString(capacity: len)

    for (var i=0; i < len; i++){
        var length = UInt32 (letters.length)
        var rand = arc4random_uniform(length)
        randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
    }

    return randomString
}

Swift 3.0 Update

斯威夫特3.0更新

func randomString(length: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let len = UInt32(letters.length)

    var randomString = ""

    for _ in 0 ..< length {
        let rand = arc4random_uniform(len)
        var nextChar = letters.character(at: Int(rand))
        randomString += NSString(characters: &nextChar, length: 1) as String
    }

    return randomString
}

#2


51  

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:

如果您喜欢的框架也有一些更方便的特性,那么请随意查看我的项目HandySwift。它还包含了一个漂亮的随机字母数字字符串解决方案:

String(randomWithLength: 8, allowedCharactersType: .alphaNumeric) // => "2TgM5sUG"

#3


39  

You may use it also in the following way:

你也可以用以下方式使用:

extension String {

    static func random(length: Int = 20) -> String {

        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {

            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.startIndex.advancedBy(Int(randomValue))])"
        }

        return randomString
    }
}

Simple usage:

简单的用法:

let randomString = String.random()

Swift 3 Syntax:

斯威夫特3语法:

extension String {

    static func random(length: Int = 20) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.characters.count))
            randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
        }
        return randomString
    }
}

Swift 4 Syntax:

斯威夫特4语法:

extension String {

    static func random(length: Int = 20) -> String {
        let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var randomString: String = ""

        for _ in 0..<length {
            let randomValue = arc4random_uniform(UInt32(base.count))
            randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
        }
        return randomString
    }
}

#4


13  

Swift:

迅速:

let randomString = NSUUID().uuidString

#5


6  

Swift 2.2 Version

斯威夫特2.2版本

// based on https://gist.github.com/samuel-mellert/20b3c99dec168255a046
// which is based on https://gist.github.com/szhernovoy/276e69eb90a0de84dd90
// Updated to work on Swift 2.2

func randomString(length: Int) -> String {
    let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let charactersArray : [Character] = Array(charactersString.characters)

    var string = ""
    for _ in 0..<length {
        string.append(charactersArray[Int(arc4random()) % charactersArray.count])
    }

    return string
}

Basically call this method that will generate a random string the length of the integer handed to the function. To change the possible characters just edit the charactersString string. Supports unicode characters too.

基本调用这个方法,它将生成一个随机字符串,它的长度是传递给函数的整数。要更改可能的字符,只需编辑字符字符串。支持unicode字符。

https://gist.github.com/gingofthesouth/54bea667b28a815b2fe33a4da986e327

https://gist.github.com/gingofthesouth/54bea667b28a815b2fe33a4da986e327

#6


5  

for Swift 3.0

斯威夫特3.0

func randomString(_ length: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let len = UInt32(letters.length)

    var randomString = ""

    for _ in 0 ..< length {
        let rand = arc4random_uniform(len)
        var nextChar = letters.character(at: Int(rand))
        randomString += NSString(characters: &nextChar, length: 1) as String
    }

    return randomString
}

#7


5  

Simple and Fast -- UUID().uuidString

简单而快速——UUID().uuidString

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

//返回从UUID创建的字符串,例如“E621E1F8-C36C-495A-93FC-0C247A3E6E5F”

public var uuidString: String { get }

public var uuidString: String {get}

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

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

Swift 3.0

斯威夫特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.

请不要与UIDevice.current.identifierForVendor混淆?uuidString它不会给出随机值。

#8


3  

func randomString(length: Int) -> String {
    // whatever letters you want to possibly appear in the output (unicode handled properly by Swift)
    let letters = "abcABC012你好吗????????????∆????∌⌘"
    let n = UInt32(letters.characters.count)
    var out = ""
    for _ in 0..<length {
        let index = letters.startIndex.advancedBy(Int(arc4random_uniform(n)))
        out.append(letters[index])
    }
    return out
}

#9


3  

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("")
}

#10


3  

Might save someone some typing, if you have the unusual case that

如果你有这种不寻常的情况,可能会给别人省点打字的钱

performance matters.

Here's an extremely simple, clear, self-contained function that caches,

这里有一个非常简单,清晰,自包含的函数,

(I think it's the sort of thing you'd just leave at global scope for simplicity.)

(我认为这是你在全球范围内为简约而做的事情。)

func randomNameString(length: Int = 7)->String{

    enum s {
        static let c = Array("abcdefghjklmnpqrstuvwxyz12345789".characters)
        static let k = UInt32(c.count)
    }

    var result = [Character](repeating: "a", count: length)

    for i in 0..<length {
        let r = Int(arc4random_uniform(s.k))
        result[i] = s.c[r]
    }

    return String(result)
}

Note that the point here is this is for a fixed, known character set - it's cached.

注意,这里的重点是这是一个固定的、已知的字符集——它被缓存。

If you need another different character set, just make another cached function,

如果您需要另一个不同的字符集,只需创建另一个缓存的函数,

func randomVowelsString(length: Int = 20)->String{
    enum s {
        static let c = Array("AEIOU".characters)
        ...

Handy tip:

方便的提示:

Note that the set "abcdefghjklmnpqrstuvwxyz12345789" avoids 'bad' characters

There is no 0, o, O, i, etc ... the characters humans often confuse.

没有0 o o i等等…人类经常混淆的角色。

This is often done for booking codes, etc.

这通常用于预订代码等。

#11


2  

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
}

#12


2  

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:

使用Swift 4.2,你最好的办法是创建一个带有你想要的字符的字符串,然后使用randomElement来选择每个字符:

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.

我在这里详细介绍了这些变化。

#13


1  

The problem with responses to "I need random strings" questions (in whatever language) is practically every solution uses a flawed primary specification of string length. The questions themselves rarely reveal why the random strings are needed, but I would challenge you rarely need random strings of length, say 8. What you invariably need is some number of unique strings, for example, to use as identifiers for some purpose.

回答“我需要随机字符串”问题(用任何语言)的问题实际上是每个解决方案都使用了一个有缺陷的主要字符串长度规范。这些问题本身很少揭示为什么需要随机字符串,但我想要挑战的是很少需要随机长度的字符串,比如8。您总是需要一些惟一的字符串,例如,作为某些用途的标识符。

There are two leading ways to get strictly unique strings: deterministically (which is not random) and store/compare (which is onerous). What do we do? We give up the ghost. We go with probabilistic uniqueness instead. That is, we accept that there is some (however small) risk that our strings won't be unique. This is where understanding collision probability and entropy are helpful.

有两种方法可以获得严格唯一的字符串:决定性的(非随机的)和存储/比较(繁重的)。我们做什么呢?我们放弃鬼魂。我们采用概率唯一性。也就是说,我们承认有一些(无论多么小的)风险,我们的字符串不会是唯一的。这就是理解碰撞概率和熵的意义所在。

So I'll rephrase the invariable need as needing some number of strings with a small risk of repeat. As a concrete example, let's say you want to generate a potential of 5 million IDs. You don't want to store and compare each new string, and you want them to be random, so you accept some risk of repeat. As example, let's say a risk of less than 1 in a trillion chance of repeat. So what length of string do you need? Well, that question is underspecified as it depends on the characters used. But more importantly, it's misguided. What you need is a specification of the entropy of the strings, not their length. Entropy can be directly related to the probability of a repeat in some number of strings. String length can't.

因此,我将把不变需求重新表述为需要一些字符串,但重复的风险很小。作为一个具体的例子,假设您希望生成500万个id。你不希望存储和比较每个新字符串,你希望它们是随机的,所以你接受重复的风险。举个例子,假设重复的风险小于1万亿次。那么你需要什么长度的字符串呢?这个问题没有得到充分的说明,因为它取决于所使用的字符。但更重要的是,它被误导了。你需要的是弦的熵,而不是它们的长度。熵可以直接与一些弦重复的概率有关。字符串长度不能。

And this is where a library like EntropyString can help. To generate random IDs that have less than 1 in a trillion chance of repeat in 5 million strings using EntropyString:

这就是像EntropyString这样的库所能提供的帮助。使用EntropyString,生成在500万个字符串中重复的概率小于一万亿分之一的随机id:

import EntropyString

let random = Random()
let bits = Entropy.bits(for: 5.0e6, risk: 1.0e12)
random.string(bits: bits)

"Rrrj6pN4d6GBrFLH4"

“Rrrj6pN4d6GBrFLH4”

EntropyString uses a character set with 32 characters by default. There are other predefined characters sets, and you can specify your own characters as well. For example, generating IDs with the same entropy as above but using hex characters:

EntropyString使用一个默认设置为32个字符的字符集。还有其他预定义的字符集,您也可以指定自己的字符。例如,生成与上面相同的熵的id,但使用十六进制字符:

import EntropyString

let random = Random(.charSet16)
let bits = Entropy.bits(for: 5.0e6, risk: 1.0e12)
random.string(bits: bits)

"135fe71aec7a80c02dce5"

“135 fe71aec7a80c02dce5”

Note the difference in string length due to the difference in total number of characters in the character set used. The risk of repeat in the specified number of potential strings is the same. The string lengths are not. And best of all, the risk of repeat and the potential number of strings is explicit. No more guessing with string length.

注意字符串长度的差异,这是由于所使用的字符集中字符总数的差异造成的。在指定的潜在字符串数量中重复的风险是相同的。字符串长度不是。最重要的是,重复的风险和字符串的潜在数量是明确的。不再猜测字符串长度。

#14


0  

If you just need a unique identifier, UUID().uuidString may serve your purposes.

如果只需要唯一标识符UUID()。uuidString可能符合您的目的。

#15


0  

This is the Swift-est solution I could come up with. Swift 3.0

这是我能想到的最快的解决办法。斯威夫特3.0

extension String {
    static func random(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let randomLength = UInt32(letters.characters.count)

        let randomString: String = (0 ..< length).reduce(String()) { accum, _ in
            let randomOffset = arc4random_uniform(randomLength)
            let randomIndex = letters.index(letters.startIndex, offsetBy: Int(randomOffset))
            return accum.appending(String(letters[randomIndex]))
        }

        return randomString
    } 
}

#16


0  

A pure Swift random String from any CharacterSet.

任何字符集的一个纯快速随机字符串。

Usage: CharacterSet.alphanumerics.randomString(length: 100)

用法:CharacterSet.alphanumerics。randomString(长度:100)

extension CharacterSet {
    /// extracting characters
    public func allCharacters() -> [Character] {
        var allCharacters = [Character]()
        for plane: UInt8 in 0 ... 16 where hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), contains(uniChar) {
                    allCharacters.append(Character(uniChar))
                }
            }
        }
        return allCharacters
    }

    /// building random string of desired length
    public func randomString(length: Int) -> String {
        let charArray = allCharacters()
        let charArrayCount = UInt32(charArray.count)
        var randomString = ""
        for _ in 0 ..< length {
            randomString += String(charArray[Int(arc4random_uniform(charArrayCount))])
        }
        return randomString
    }
}

The allCharacters() is based on Martin R answer.

allCharacters()基于Martin R的回答。

#17


0  

Swift :

迅速:

Just simplified for understandable way in swift.

只是简化了,以理解的方式迅速。

func randomString(_ length: Int) -> String {

    let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
    var randomString = ""

    for _ in 1...length{

        let random = arc4random_uniform(UInt32(master.count))
        randomString.append(String(master[Int(random)]))
    }
    return randomString
}

#18


0  

Updated for Swift 4. Use a lazy stored variable on the class extension. This only gets computed once.

更新迅速4。在类扩展中使用惰性存储变量。这个只计算一次。

extension String {

    static var chars: [Character] = {
        return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".map({$0})
    }()

    static func random(length: Int) -> String {
        var partial: [Character] = []

        for _ in 0..<length {
            let rand = Int(arc4random_uniform(UInt32(chars.count)))
            partial.append(chars[rand])
        }

        return String(partial)
    }
}

String.random(length: 10) //STQp9JQxoq

#19


-1  

func randomUIDString(_ wlength: Int) -> String {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var randomString = ""

    for _ in 0 ..< wlength {
        let length = UInt32 (letters.length)
        let rand = arc4random_uniform(length)
        randomString = randomString.appendingFormat("%C", letters.character(at: Int(rand)));
    }

    return randomString
}