Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Swift] Generic #72

Closed
seungchan2 opened this issue Jun 4, 2022 · 0 comments
Closed

[Swift] Generic #72

seungchan2 opened this issue Jun 4, 2022 · 0 comments
Assignees
Labels

Comments

@seungchan2
Copy link
Owner

seungchan2 commented Jun 4, 2022

제네릭

var num1 = 10
var num2 = 20

// 두 숫자를 스왑(서로 교환)하는 함수의 정의
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let tempA = a
    a = b
    b = tempA
}

// 위에서 정의한 함수의 실행
swapTwoInts(&num1, &num2)

print(num1)
print(num2)

서로를 swap하는 함수를 하나 만듬

inout 키워드를 사용해서 파라미터의 값을 바꿔줌

파라미터는 값 타입이라서 바꿀 수 없지만 inout 키워드를 사용한다면 바꿀 수 있음

inout 톺아보기

지금 inout이 중요한 게 아니라 제네릭을 왜 써야 하는지 보겠음

위에 swap 함수를 Double, String 등 다양한 타입으로 교환하고 싶다면 어떻게 할거임?

계속해서 만들어서 사용하는 것은 엄청 비효율적임

// Double을 스왑하는 함수의 정의

func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {
    let tempA = a
    a = b
    b = tempA
}

// (정수가 아닌) 문자열을 스왑하는 함수의 정의

func swapTwoStrings(_ a: inout String, _ b: inout String) {
    let tempA = a
    a = b
    b = tempA
}

뭐 이런식으로 만들 수 있겠지만 에바임 ㅋㅋ

그래서 사용하는 것이 제네릭임

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {      // 플레이스홀더의 역할(표시 역할일뿐) (같은 타입이어야함)
    let tempA = a
    a = b
    b = tempA
}
@seungchan2 seungchan2 changed the title [Swift] 제네릭 [Swift] Generic Jun 7, 2022
@seungchan2 seungchan2 self-assigned this Jun 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant