Skip to content

Latest commit

ย 

History

History
50 lines (37 loc) ยท 1.07 KB

Generic.md

File metadata and controls

50 lines (37 loc) ยท 1.07 KB

Generic

ํƒ€์ž…์— ์˜์กดํ•˜์ง€ ์•Š๋Š” ๋ฒ”์šฉ์ฝ”๋“œ๋ฅผ ์œ„ํ•ด์„œ ์กด์žฌ ํ•˜๋ฉฐ ์–ด๋–ค ํƒ€์ž…์ด ๋“ค์–ด์™€๋„ ๊ดœ์ฐฎ์€ ์ฝ”๋“œ์ด๋‹ค.

func ํ•จ์ˆ˜์ด๋ฆ„<ํƒ€์ž…์ด๋ฆ„>(input: ์‹ค์ œ ์ž…๋ ฅ๋ฐ›์€ ํƒ€์ž…) {
    input -> ํƒ€์ž… ๋ณ€์ˆ˜
}

์˜ˆ๋ฅผ ๋“ค์–ด Int๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์„ ๊ฐ–๋Š” ๊ตฌ์กฐ์ฒด๋ฅผ ํ•œ๋ฒˆ ๋งŒ๋“ค์–ด ๋ณด์ž

struct MyStack {
    var data: [Int] = []

    mutating func insertValue(input: Int) {
        data.append(input)
    }

    func showData() {
        data.forEach { item in
            print(item)
        }
    }
}

๊ทธ๋Ÿฐ๋ฐ, Intํ˜•์ด ์•„๋‹Œ String, Float๋“ฑ ๋‹ค๋ฅธ ๊ฐ’์„ ๊ฐ–๋Š” ๊ตฌ์กฐ์ฒด๋ฅผ ๋งŒ๋“ค๋ ค๊ณ  ํ•œ๋‹ค๋ฉด ๊ณ„์†ํ•ด์„œ ๋งŒ๋“ค์–ด์•ผ ํ• ๊นŒ?

์ด ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด Generic์ด๋‹ค.

struct MyGenericStack<T> {
    var data: [T] = []

    mutating func insertValue(input: T) {
        data.append(input)
    }

    func showData() {
        data.forEach { item in
            print(item)
        }
    }

}

์ด๋ ‡๊ฒŒ ๋งŒ๋“ ๋‹ค๋ฉด ์—ฌ๋Ÿฌ๋ฒˆ ๋งŒ๋“ค ๋ป” ํ–ˆ๋˜ ๊ฑธ ํ•œ ์ฝ”๋“œ๋กœ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.