Generate random alphanumeric string in Swift

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

How can I generate a random alphanumeric string in Swift?

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

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

    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
    
    0 讨论(0)
  • 2020-11-27 10:23

    A pure Swift random String from any CharacterSet.

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

    extension CharacterSet {
        /// extracting characters
        /// https://stackoverflow.com/a/52133647/1033581
        public func characters() -> [Character] {
            return codePoints().compactMap { UnicodeScalar($0) }.map { Character($0) }
        }
        public func codePoints() -> [Int] {
            var result: [Int] = []
            var plane = 0
            for (i, w) in bitmapRepresentation.enumerated() {
                let k = i % 8193
                if k == 8192 {
                    plane = Int(w) << 13
                    continue
                }
                let base = (plane + k) << 3
                for j in 0 ..< 8 where w & 1 << j != 0 {
                    result.append(base + j)
                }
            }
            return result
        }
    
        /// building random string of desired length
        /// https://stackoverflow.com/a/42895178/1033581
        public func randomString(length: Int) -> String {
            let charArray = characters()
            let charArrayCount = UInt32(charArray.count)
            var randomString = ""
            for _ in 0 ..< length {
                randomString += String(charArray[Int(arc4random_uniform(charArrayCount))])
            }
            return randomString
        }
    }
    

    The characters() function is my fastest known implementation.

    0 讨论(0)
  • 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..<length {
            let r = Int(arc4random_uniform(s.k))
            result[i] = s.c[r]
        }
        
        return String(result)
    }
    

    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.

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

    Swift 5.0

    // Generating Random String
    func randomString(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
    // Calling to string
    label.text = randomString(length: 3)
    
    0 讨论(0)
提交回复
热议问题