Generate random alphanumeric string in Swift

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

How can I generate a random alphanumeric string in Swift?

22条回答
  •  余生分开走
    2020-11-27 10:24

    UPDATED 2019.

    In the unusual case that

    performance matters.

    Here is an extremely clear function that caches:

    func randomNameString(length: Int = 7)->String{
        
        enum s {
            static let c = Array("abcdefghjklmnpqrstuvwxyz12345789")
            static let k = UInt32(c.count)
        }
        
        var result = [Character](repeating: "-", count: length)
        
        for i in 0..

    This is for when you have a fixed, known character set.

    Handy tip:

    Note that "abcdefghjklmnpqrstuvwxyz12345789" avoids 'bad' characters

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

    This is often done for booking codes and similar codes which human customers will use.

提交回复
热议问题