在数组索引上创建随机字符串

Create random string on index of array

func randomStringWithLength (len : Int) -> NSString {

    let answer : NSString =  ArrAnswer.objectAtIndex(0) as! NSString
    let letters : NSString = answer
    print(letters)
    let randomString : NSMutableString = NSMutableString(capacity: len)

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

    }

    return randomString
}

我已经试过了, 某些后者在每次或某些时候都会丢失到转换后的字符串中,两次或三次打印后者。

我认为这是最好的方法,除非其他人有其他方法,否则您可能需要根据需要调整此代码:

let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

我不确定你到底需要什么。如果你需要随机化字符串中的字符,你可以使用这样的东西

import Foundation
let str = "abcdef"

// returns string with random order of characters
func randomize(str: String)->String {
    var chars = str.characters.map{ [=10=] }
    let c = UInt32(chars.count)
    if c < 2 { return str}

    for i in 0..<(c - 1) {
        let j = arc4random_uniform(c)
        if i != j {
            swap(&chars[Int(i)], &chars[Int(j)])
        }
    }
    return chars.reduce("", combine: { (str, c) -> String in
        str + String(c)
    })
}
for i in 0...10 {
    print(randomize(str))
}
/* prints

dcbeaf
edcabf
cebadf
adcbef
dacbef
dceabf
eacbdf
adebcf
adcbef
bedcaf
daebcf

*/