Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

Generic에 대해 설명하시오. #28

Open Do-hyun-Kim opened 10 months ago

Do-hyun-Kim commented 10 months ago

Generic에 대해 설명하시오.

var numberOne: Double = 5.0
var numberTwo: Double = 10.0

swapToDoubles(&numberOne, &numberTwo)
print("numberOne value : \(numberOne) numberTwo value : \(numberTwo)")

var stringOne: String = "Jenny"
var stringTwo: String = "Hyun"
swapToStrings(&stringOne, &stringTwo)

print("stringOne value : \(stringOne) stringTwo value : \(stringTwo)")

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

swapTwoValues(&numberOne, &numberTwo)
print("genericOne value : \(numberOne) genericTwo value : \(numberTwo)")

Generic Function

Generic Functions

Generic Type Parameter

Generic Types

struct JennyStack<Element> {
    var items: [Element] = []

    mutating func push(_ item: Element) {
        items.append(item)
    }

    mutating func pop() -> Element {
        return items.removeLast()
    }

}

var myStack: JennyStack<Int> = JennyStack()
myStack.push(1)
print("append Item: \(myStack)")
// append Item: JennyStack<Int>(items: [1])

Extending a Generic Type

extension JennyStack {
    var topItem: Element? {
        return items.isEmpty ? nil : items[items.count - 1]
    }
}

print("myStack Top Item: \(myStack.topItem)")

Generic Type Constraints

class SomeClass {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

protocol SomeProtocol {
    var name: String { get }
    var age: Int { get }
}

func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
    // 함수 구현
}

TMI Generics

TMI Generics Specialization

📝 참고 사이트

Hminchae commented 10 months ago

제네릭 (Generics)

제네릭 타입:
타입이름<타입 매개변수>

제네릭 메서드/함수:
메서드이름<타입 매개변수> (메서드 매개변수...) {...}

}

vichye-1 commented 10 months ago

generic이란?

사용법

  1. 제네릭 함수 (Generic Function)
    • <>를 이용해서 안에 타입처럼 사용할 이름(T)을 선언해주면, 그 뒤로 해당 이름(T)을 타입처럼 사용할 수 있다.
    • 타입 파라미터 이름을 선언할 때 가독성을 위해 T, V와 같은 단일 문자, 혹은 Upper Camel Case를 사용한다.
    • 타입 파라미터는 여러 개를 선언 할 수 있다 → , 사용
      • 예) func swapTwoValues<One, Two> {...}
    • 실제 함수를 호출할 때 Type Parameter인 T의 타입이 결정된다.
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let tempA = a
    a = b
    b = tempA
}

var someInt = 1
var anotherInt = 2
swapTwoValues(&someInt, &anotherInt)
print(someInt, anotherInt)
// 2 1

var someString = "Hi"
var anotherString = "Bye"
swapTwoValues(&someString, &anotherString)
print(someString, anotherString)
// Bye Hi
  1. 제네릭 타입(Generic Type)
    • 구조체, 클래스, 열거형, 인스턴스 등에도 선언할 수 있다.
// 구조체에 선언한 예 (stack을 generic으로 만듦)
struct Stack<T> {
    let items: [T] = []

    mutating func push(_ item: T) {...}
    mutating func pop() -> T {...}
}
let array1: Array<Int> = .init()
let array2 = Array<Int>.init()
print(array1, array2)
// [] []

참고

ronick-grammer commented 10 months ago

Generic이란 (작성중)

struct Stack<T> {
    var items: [T] = []
    mutating func push(_ item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}

Generic의 타입 추론

generic 정의 객체를 생성하거나 generic 메서드를 호출할 때 Swift 에서는 생성/호출 직전, generic 타입과 실제 데이터 타입을 바인딩(binding) 하게 된다.

타입 제약

📝 참고 사이트