Swift Note

兴趣是最好的老师

Swift 获取随机字符串

很常用的功能,随手记一下。

代码来自于 https://gist.github.com/szhernovoy/276e69eb90a0de84dd90

各个 Swift 的版本,从中也可以看到 Swift 语法的演变,嗯,蛮蛋疼的,哈哈

Swift 1.0

func randomString(len:Int) -> String {  
    let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var c = Array(charSet)
    var s:String = ""
    for n in (1...10) {
        s.append(c[Int(arc4random()) % c.count])
    }
    return s
}

Swift 2.0

func randomString(length: Int) -> String {  
    let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let charactersArray = Array(arrayLiteral: charactersString)

    var string = ""
    for _ in 0..<length {
        string += charactersArray[Int(arc4random()) % charactersArray.count]
    }

    return string
} 

Swift 2.3 - 3.0

func randomString(length:Int) -> String {  
        let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var c = charSet.characters.map { String($0) }
        var s:String = ""
        for _ in (1...length) {
            s.append(c[Int(arc4random()) % c.count])
        }
        return s
    }

神飞

没有什么能够阻挡,我对自由的向往