生成随机string后的奇怪返回值(Swift 3)
我创build了一个方法,可以生成并返回一个包含字母和数字的随机string,但由于某种原因,我只能得到一个带有数字的string,并且string的长度并不接近我所要求的。 已经返回的string的一些示例:“478388299949939566”(插入18作为长度),“3772919388584334”(插入9作为长度),“2293010089409293945”(插入6作为长度)。 任何人都可以看到我在这里错过了什么?
func generateRandomStringWithLength(length:Int) -> String { let randomString:NSMutableString = NSMutableString(capacity: length) let letters:NSMutableString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for index in 0...length { let randomIndex:Int = Int(arc4random_uniform(UInt32(62))) randomString.append("\(letters.character(at: randomIndex))") } return String(randomString) }
你的问题在这里:
letters.character(at: randomIndex)
它的函数返回给定的UTF-16代码单元索引处的字符,而不仅仅是一个字符
这是我的版本,我想它更快。
func generateRandomStringWithLength(length: Int) -> String { var randomString = "" let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for _ in 1...length { let randomIndex = Int(arc4random_uniform(UInt32(letters.characters.count))) let a = letters.index(letters.startIndex, offsetBy: randomIndex) randomString += String(letters[a]) } return randomString } generateRandomStringWithLength(length: 5)
用这个:
func generateRandomStringWithLength(length:Int) -> String { let randomString:NSMutableString = NSMutableString(capacity: length) let letters:NSMutableString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var i: Int = 0 while i < length { let randomIndex:Int = Int(arc4random_uniform(UInt32(letters.length))) randomString.appendString("\(Character( UnicodeScalar( letters.characterAtIndex(randomIndex))))") i += 1 } return String(randomString) }
调用generateRandomStringWithLength方法:
print(generateRandomStringWithLength(5)) print(generateRandomStringWithLength(10)) print(generateRandomStringWithLength(20)) print(generateRandomStringWithLength(7)) print(generateRandomStringWithLength(14))
示例输出:
GIrqb nWmieQRVdk r0It9V1xkGFRa2HVwtCw RLIRuVI nXnFGV2LQ3CjbD