How to use XOR to swap two characters in a string in Swift

1 Answer

0 votes
import Foundation

/// Swaps two ASCII characters in a string in-place using the XOR swap algorithm.
///
/// - Note: This function demonstrates bitwise XOR swapping for educational purposes.
///   In production Swift code, preferred idioms such as `text.swapAt(index1, index2)`
///   or tuple assignment `(a, b) = (b, a)` are strongly recommended for safety,
///   clarity, and performance.
///
/// - Parameters:
///   - text: The string containing the characters to swap (passed in-place via `inout`).
///   - left: Zero-based integer index of the first character.
///   - right: Zero-based integer index of the second character.
func xorSwapCharacters(_ text: inout String, left: Int, right: Int) {
    var bytes = Array(text.utf8)

    // Guard clause for empty string or out-of-bounds indices
    guard !bytes.isEmpty, left >= 0, right >= 0, left < bytes.count, right < bytes.count else {
        return
    }

    // XOR swap fails if left == right because (x ^ x) evaluates to 0
    guard left != right else {
        return
    }

    // Bitwise XOR swap on UInt8 elements
    bytes[left] ^= bytes[right]
    bytes[right] ^= bytes[left]
    bytes[left] ^= bytes[right]

    // Construct valid UTF-8 string back from modified bytes
    if let updatedText = String(bytes: bytes, encoding: .utf8) {
        text = updatedText
    }
}

func main() {
    var text = "hello"

    print("Before: \(text)")

    xorSwapCharacters(&text, left: 1, right: 4)

    print("After:  \(text)")
}

main()


/*
run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...