:
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()
}
}
は、これまでのカードゲームをプレイ? "シャッフル"という言葉を聞いたことがありますか?キャラクターをシャッフルし、最初の4つを取り除く。 – matt
http://stackoverflow.com/questions/27761557/shuffling-a-string-in-swift(そのうちの質問は実際に重複しています) – matt
またはこの記事:http://stackoverflow.com/questions/26845307/文字列の中で文字列を生成する – iWheelBuy