如何使用:
let randomString = "ABCDEF".random(length: 3)!
返回值是可選的,因爲該長度可能超過提供的字符串的長度。
退房全面實施:
import UIKit
import PlaygroundSupport
extension MutableCollection where Indices.Iterator.Element == Index {
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}
extension Sequence {
func shuffled() -> [Iterator.Element] {
var result = Array(self)
result.shuffle()
return result
}
}
extension String {
func random(length: Int) -> String? {
let uniqueCharacters = Array(Set(characters.map({ String($0) })))
guard length <= uniqueCharacters.count else { return nil }
guard length > 0 else { return nil }
return uniqueCharacters[0..<length].shuffled().joined()
}
}
自從玩卡片遊戲?你有沒有聽說過「洗牌」這個概念?洗牌的人,並處理前四個。 – matt
http://stackoverflow.com/questions/27761557/shuffling-a-string-in-swift(其中你的問題實際上只是一個副本) – matt
或這一個:http://stackoverflow.com/questions/26845307/生成隨機字母數字字符串在迅速 – iWheelBuy