count
가있는 IndexDistance
를 반환 유형이 거리를 설명 두 컬렉션 인덱스 사이. IndexDistance
이 인 것이 요구되고, Int
일 필요는없고, 은 Index
과 다를 수있다. 따라서 범위 0..<count - 1
을 으로 만들 수 없습니다.
용액 startIndex
및 endIndex
대신 0
및 count
을 사용하는 것이다
extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
if i != j {
swap(&self[i], &self[j])
}
}
}
}
다른 이점이 또한 어레이 슬라이스가 올바르게 작동하는지이다 (첫 번째 요소의 인덱스가 필요없는 경우에는 제로).
extension Collection {
/// Return a copy of `self` with its elements shuffled
func shuffled() -> [Iterator.Element] {
var list = Array(self)
list.shuffle()
return list
}
}
업데이트 : 새로운 "Swift API Design Guidelines"에 따른 shuffle()
배열을 반환 비 돌연변이 대응하는 돌연변이 셔플 방법 및 shuffled()
에 대해 "적절한"이름
참고 그 사이에 Swift 3 버전이 How do I shuffle an array in Swift?에 추가되었습니다 (훨씬 더 일반적인).
은
스위프트 4 (엑스 코드 9) 들어 하나의 컬렉션의
swapAt()
메소드를 호출하여
swap()
함수 호출을 대체한다. 은 또한
Index
유형에 대한 제한이 더 이상 필요하지 않습니다 :
extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in indices.dropLast() {
let diff = distance(from: i, to: endIndex)
let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
swapAt(i, j)
}
}
}
자세한 내용에 대한 swapAt
에 대한 SE-0173 Add MutableCollection.swapAt(_:_:)
를 참조하십시오.
에 https : // 유래합니다.com/a/27261991/2303865 –
[Swift에서 배열을 임의로 섞는 방법] (https://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift)) –
Swift 3에 대한 참조가 업데이트되었으므로이 질문은 더 이상 사용되지 않습니다. –