์ ๋ค๋ฆญ(Generics)
์ ์ฐํ๊ณ ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ํจ์์ ํ์ ์ ์ฝ๋๋ฅผ ์์ฑํ๋ ๊ฒ์ ๊ฐ๋ฅํ๊ฒ ํจ
์ธ์๊ฐ์ ํ์ ๋ง ๋ค๋ฅด๊ณ ๋์ผํ ๊ธฐ๋ฅ์ ์ํํ๋ ํจ์๋ฅผ ํ๋๋ก ๋ง๋ค ์ ์์
์ ๋ค๋ฆญ ํจ์(Generic Functions)
ํจ์๋ช ๋ค์ ํ์ ์ด๋ฆ placeholder์ธ T๋ฅผ ์ ์ธํ๊ณ a,b ํ๋ผ๋ฏธํฐ๋ฅผ T๋ก ์ ์ธ
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// someInt is now 107, and anotherInt is now 3
var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// someString is now "world", and anotherString is now "hello"
ํ์ ํ๋ผ๋ฏธํฐ(Type Parameters)
placeholder ํ์ ์ ์ด๋ฆ์ ๋ช ์ํ๊ณ ํจ์๋ช ๋ฐ๋ก ๋ค์ ์ ์ด์ค ํ ๊บฝ์๋ก ๋ฌถ์ด ์ฌ์ฉ
ํ๋ผ๋ฏธํฐ ์ด๋ฆ ์ง๊ธฐ
element ๊ฐ์ ์๊ด๊ด๊ณ๊ฐ ์๋ ๊ฒฝ์ฐ ์๋ฏธ ์๋ ์ด๋ฆ์ ๋ง๋ผ๋ฏธํฐ ์ด๋ฆ์ผ๋ก ์ฌ์ฉ
๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ T, U, V์ ๊ฐ์ ๋จ์ผ ๋ฌธ์๋ฅผ ํ๋ผ๋ฏธํฐ ์ด๋ฆ์ผ๋ก ์ฌ์ฉ
์ ๋ค๋ฆญ ํ์
์ ๋ค๋ฆญ ํจ์์ ์ถ๊ฐ๋ก ์ ๋ค๋ฆญ ํ์ ์ ์ ๊ฐ๋ฅ
์ต์คํ ์ ์ ์ด์ฉํด ์ ๋ค๋ฆญ ํ์ ์ ํ์ฅํ ์ ์์
struct Stack<Element> {
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
extension Stack {
var topItem: Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
ํ์ ์ ํ
ํน์ ํ์ ์ด ๋ฐ๋์ ์ด๋ค ํ๋กํ ์ฝ์ ๋ฐ๋ผ์ผํ๋ ๊ฒฝ์ฐ ํน์ ํด๋์ค๋ฅผ ์์ํ๊ฑฐ๋, ํน์ ํ๋กํ ์ฝ์ ๋ฐ๋ฅด๊ฑฐ๋ ํฉ์ฑํ๋๋ก ๋ช ์ ๊ฐ๋ฅ
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
์ฐ๊ด ํ์
ํ๋กํ ์ฝ์ ์ผ๋ถ๋ถ์ผ๋ก ํ์ ์ placeholder ์ด๋ฆ์ ๋ถ์ฌ
ํน์ ํ์ ์ ๋์ ์ผ๋ก ์ง์ ํด ์ฌ์ฉ ๊ฐ๋ฅ
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
struct Stack<Element>: Container {
// original Stack<Element> implementation
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(_ item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}
์ ๋ค๋ฆญ์ Where์
๊ธฐ๋ณธ ์ ๋ค๋ฆญ, ์ ๋ค๋ฆญ์ ์ต์คํ ์ , ์ฐ๊ดํ์ , ์๋ธ์คํฌ๋ฆฝํธ์์๋ where ๊ตฌ๋ฌธ์ ์ฌ์ฉํด ์กฐ๊ฑด์ ๊ฑธ ์ ์์
func allItemsMatch<C1: Container, C2: Container>
(_ someContainer: C1, _ anotherContainer: C2) -> Bool
where C1.Item == C2.Item, C1.Item: Equatable {
// Check that both containers contain the same number of items.
if someContainer.count != anotherContainer.count {
return false
}
// Check each pair of items to see if they're equivalent.
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// All items match, so return true.
return true
}
'โจ๏ธ Language > swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ์คํ(Stack) ๊ตฌํํ๊ธฐ (0) | 2024.09.27 |
---|---|
[Swift] ์๋ ์ฐธ์กฐ ์นด์ดํธ (0) | 2024.04.02 |
[Swift] ํ๋กํ ์ฝ (0) | 2024.03.29 |
[Swift] ์๋ฌ ์ฒ๋ฆฌ (0) | 2024.03.28 |
[Swift] ์ต์ ๋ ์ฒด์ด๋ (0) | 2024.03.26 |