Not a direct answer to your question but you can get all permutations (translated from java to Swift) as follow:
public extension RangeReplaceableCollection {
func permutations() -> [SubSequence] {
isEmpty ? [] : permutate(.init())
}
private func permutate(_ subSequence: SubSequence) -> [SubSequence] {
var permutations = isEmpty ? [subSequence] : []
indices.forEach {
permutations += (self[..<$0] + self[$0...].dropFirst())
.permutate(subSequence + CollectionOfOne(self[$0]))
}
return permutations
}
}
let str = "ABCD"
print(str.permutations()) // "["ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA"]
"
Per-mutating a substring
print("ABCD".dropLast().permutations()) // ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]
"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…