[swift] 타입 캐스팅을 이용한 다양한 알고리즘 구현

알고리즘 문제를 풀 때 Swift에서 다양한 데이터 타입을 다뤄야 하는 경우가 많습니다. 타입 캐스팅을 이용하면 강력한 알고리즘을 구현하는 데 도움이 될 수 있습니다. 이번 포스트에서는 Swift에서 타입 캐스팅을 활용하여 다양한 알고리즘을 구현하는 방법에 대해 알아보겠습니다.

타입 캐스팅이란?

타입 캐스팅은 인스턴스의 타입을 확인하거나 다른 타입으로 변환하는 것을 말합니다. 이를 통해 런타임 시에 인스턴스의 타입을 체크하고 적합한 코드를 실행할 수 있습니다.

다형성을 이용한 다이나믹 프로그래밍 구현

class Shape {
    func draw() {
        // draw shape
    }
}

class Circle: Shape {
    override func draw() {
        // draw circle
    }
}

class Square: Shape {
    override func draw() {
        // draw square
    }
}

let shapes: [Shape] = [Circle(), Square(), Circle(), Square()]

for shape in shapes {
    if let circle = shape as? Circle {
        circle.draw()
    } else if let square = shape as? Square {
        square.draw()
    }
}

위 예시에서는 Shape 클래스를 상속받는 CircleSquare 클래스를 만들고, 배열에 이들을 담아 루프를 돌면서 각 도형의 draw() 메서드를 호출합니다. 이때, 타입 캐스팅을 통해 도형의 실제 타입을 확인하여 적절한 도형을 그리도록 할 수 있습니다.

타입 변환을 활용한 정렬 알고리즘 구현

protocol Sortable {
    func isLess(than: Self) -> Bool
}

extension Int: Sortable {
    func isLess(than: Int) -> Bool {
        return self < than
    }
}

extension String: Sortable {
    func isLess(than: String) -> Bool {
        return self.compare(than) == .orderedAscending
    }
}

func selectionSort<T: Sortable>(_ arr: [T]) -> [T] {
    var sortedArr = arr
    for i in 0..<sortedArr.count {
        var minIndex = i
        for j in i+1..<sortedArr.count {
            if sortedArr[j].isLess(than: sortedArr[minIndex]) {
                minIndex = j
            }
        }
        if i != minIndex {
            sortedArr.swapAt(i, minIndex)
        }
    }
    return sortedArr
}

let numbers = [5, 2, 7, 3, 9, 1]
let sortedNumbers = selectionSort(numbers)
// sortedNumbers: [1, 2, 3, 5, 7, 9]

let words = ["apple", "orange", "banana", "grape", "cherry"]
let sortedWords = selectionSort(words)
// sortedWords: ["apple", "banana", "cherry", "grape", "orange"]

위 예시에서는 Sortable 프로토콜과 여러 타입에 대한 확장을 통해 타입 캐스팅 없이도 일반적인 정렬 알고리즘을 사용할 수 있습니다.

타입 캐스팅을 적절히 활용하면 다양한 알고리즘을 구현하고 유연한 프로그래밍을 할 수 있습니다. Swift에서의 타입 캐스팅을 잘 활용하여 프로그래밍을 할 때 유용하게 활용해보세요!

참고 자료: