iOS Swift - Generic

longlivedrgn·2022년 9월 9일
0

swift문법

목록 보기
19/36
post-thumbnail

Gneric Function

  • 어떠한 타입으로든 하나의 함수로 표현할 수 있다.

예) 만약 내가 파라미터로 들어온 두 인자의 값을 바꾸는 함수를 만들었다고 해보자

func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
 
func swapTwoDoubles(inout a: Double, inout b: Double) {
    let temporaryA = a
    a = b
    b = temporaryA
}

-> 위 코드는 인자가 Int일 때, Double일 때 둘 다 생성을 해야지 두개의 자료형을 커버할 수 있다.

근데, 앞서 말한 것과 같이 Generic의 경우 어떠한 타입이든지 하나의 함수로 표현을 할 수가 있다.

즉) 아무 자료형이나 다 받을 수 있는 것이다.

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

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 //2
b //1

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

※ inou/ & 과 관련된 참고자룥
-> https://hyunsikwon.github.io/swift/Swift-Inout-01/

Generic constraints

  • 아래의 코드는 에러가 난다. 왜냐하면 generic type의 경우, ==라는 연산자가 없기에 Equatable이라는 protocol을 만족해야지만 == 연산자를 사용할 수 있다. 따라서 <T:Equatable>을 하면 Equatable protocol을 만족하는 파라미터만 받을 수 있다.
func swapValue<T>(lhs: inout T, rhs: inout T) {
    if lhs == rhs {
        return
    }
    let tmp = lhs
    lhs = rhs
    rhs = tmp
}

Generic Type/ Associated Types는 다시 공부해보기

0개의 댓글