生成随机字符串后的奇怪返回值(Swift 3)

时间:2016-09-19 05:41:04

标签: ios swift string random generator

我创建了一个生成并返回字母和数字的随机字符串的方法,但由于某种原因,我只得到一个带数字的字符串,字符串的长度不接近我要求的字符串是。返回的一些字符串示例:“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)
}

2 个答案:

答案 0 :(得分:3)

你的问题在这里:

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)

答案 1 :(得分:1)

使用此:

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