swift

swift - Generic #1 (Function, Constraints)

행복하게사는게꿈 2021. 1. 13. 10:06

// <T> : Type Parameter

func swapValue<T>(lhs: inout T, rhs: inout T) {
   let tmp = lhs
   lhs = rhs
   rhs = tmp
}

a = 1
b = 2
swapValue(lhs: &a, rhs: &b)
a
b

var c = 1.2
var d = 3.4
swapValue(lhs: &c, rhs: &d)
c
d

// 제네릭 형식 제약

func swapValue<T: Equatable>(lhs: inout T, rhs: inout T) {
    // 파라미터로 비교 기능이 구현되지 않은 타입이 올 수 도 있기 때문에 직접 비교를 구현해주지 않으면 에러 발생
    // T: Equatable -> Equatable 프로토콜을 채용한 자료형만 허락함
    print("Genric version")
    if lhs == rhs { return }
    
   let tmp = lhs
   lhs = rhs
   rhs = tmp
}

// 대소문자를 무시하고 비교하고 싶다면 특수화를 통해서 특정 형식을 위한 메소드를 구현한다.
// String 형식을 위한 구현
func swapValue(lhs : inout String, rhs: inout String) {
    print("specialized version")
    
    if lhs.caseInsensitiveCompare(rhs) == .orderedSame {
        return
    }
   
    let tmp = lhs
    lhs = rhs
    rhs = tmp
}

var a = 1
var b = 2
swapValue(lhs: &a, rhs: &b)

var c = "Swift"
var d = "Programming"
swapValue(lhs: &c, rhs: &d)