shuffle a string in swift

Here's one way to shuffle a string in Swift using the Fisher-Yates shuffle algorithm:

main.swift
var str = "Hello, World!"

// Convert the string to an array of characters
var chars = Array(str)

// Perform Fisher-Yates shuffle algorithm on the array
for i in 0..<chars.count {
    let j = Int(arc4random_uniform(UInt32(chars.count - i))) + i
    if i != j {
        swap(&chars[i], &chars[j])
    }
}

// Convert the array back to a string
str = String(chars)

print(str) // Outputs a shuffled version of the original string
429 chars
18 lines

In this code, we first convert the input string into an array of characters. Then, we loop through the array and randomly swap each character with another character in the array. Finally, we convert the shuffled array back into a string and output the result.

gistlibby LogSnag