[Swift] AssociatedType
์๋ ํ์ธ์ ๐ ์ค๋์ AssociatedType์ ๋ํด์ ์์๋ณผ๊ฑฐ์์!
๋ง ๊ทธ๋๋ก ๊ด๋ จ๋ ํ์ ..? ์ฐ๊ด๋ ํ์ ..? ๊ทธ๋ฐ๊ฑด๋ฐ, ์ฌ์ค์ Generic์์ placeholder ํ์ ๊ฐ์๊ฑฐ์์!!
๋ฌด์จ๋ง์ด๋.. ์์๋ฅผ ๋ค์ด์ ๋ด ์๋ค์!!
protocol Appendable {
var collection: [String] { get set }
func append(_ item: String)
}
class StringArray: Appendable {
var collection: [String] = []
func append(_ item: String) {
collection.append(item)
}
}
Appendable์ด๋ผ๋ ์ด๋ค Array์ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ ์ ์๋ ๊ธฐ๋ฅ์ ๊ฐ์ง protocol์ด ์์ด์.
์ด Appendable์ด๋ผ๋ ํ๋กํ ์ฝ์ ์ฑํํ๋ StringArray๋ผ๋ classํ์ ์์, ํ๋กํ ์ฝ์ ์ค์ํ๋ต์๊ณ ๋ฉ์๋์ ํ๋กํผํฐ๋ฅผ ์ ์ํด์ฃผ๋๋ฐ์!
์ฐ๋ฆฌ๊ฐ ํ๋กํ ์ฝ์ ์ฐ๋ฉด์ ์ํ๋๊ฑด ์ด๊ฒ ์๋๊ฒ ์ฃ ~?
class IntArray: Appendable {
var collection: [Int] = []
func append(_ item: Int) {
collection.append(item)
}
}
์ด๋ฐ๊ฒ๋ ๊ฐ์ด ์ฐ๊ณ ์ถ์์์~~~ ๐
๊ทผ๋ฐ ์ง๊ธ ์ํ๋ก๋ฉด IntArray๋ ์๋ฌ๋ฅผ ์ถ๋ ฅํ ๊ฑฐ์์. Intํ์ ์ ๋ค๋ฃฐ ์ ์๋ ๊ธฐ๋ฅ์ด Appendable ํ๋กํ ์ฝ์๋ ์๊ธฐ ๋๋ฌธ์ด์์.
์ด๋!! ์ธ ์ ์๋๊ฒ ๋ฐ๋ก associatedType ์ด์์.
protocol Appendable {
associatedtype SomeType
var collection: [SomeType] { get set }
func append(_ item: SomeType)
}
์ฒ์์ associatedtype์ ์๊ฐํ ๋ ์ด๋ค Generic์ Placeholder๊ฐ์๊ฑฐ๋ผ๊ณ ํ์ฃ ~? ์ด๋ ๊ฒ์!!
"์ด๋ค ํ์ ์ด๋ ์๊ด์์ด~ ์ฌ์ฉํ ๋๋ง ๋ช ์ํด์ฃผ๋ฉด ๋ผ"
class StringArray: Appendable {
var collection: [String] = []
func append(_ item: String) {
collection.append(item)
}
}
class IntArray: Appendable {
var collection: [Int] = []
func append(_ item: Int) {
collection.append(item)
}
}
๊ทธ๋ฌ๋ฉด ์ฐ๋ฆฌ๊ฐ ์ํ๋ ์ด๋ฐ๊ฒ ๊ฐ๋ฅํ๊ฒ ๋์!!
๊ทผ๋ฐ ํ๋กํ ์ฝ์ ์ ์ํด์ผ ํ ํ๋กํผํฐ๋ ๋ฉ์๋๊ฐ ๋ง์ผ๋ฉด.. ๊ทธ๋ ํ๋ํ๋ Int, String ์ณ์ค๊ฑด๊ฐ์~~?
์ฐ๋ฆฌ๋ ์๋์์ฑ์ ๋ ์ฌ์ฉํด์ผ ํ์์์! ๐ง๐ป
class StringArray: Appendable {
typealias SomeType = String
var collection: [String]
func append(_ item: String) {
<#code#>
}
}
๋จผ์ ํ๋ํ๋ ์ ์ํ๊ธฐ ์ ์, typealias๋ฅผ ํตํด placeholder๋ก ์ด๋ค ํ์ ์ ์ธ๊ฑด์ง๋ฅผ ์ ์ํด๋ฒ๋ฆฌ๋๊ฑฐ์์!
๊ทธ๋ฌ๋ฉด ํ๋กํ ์ฝ์ ์ค์ํ๊ธฐ ์ํด ํ๋กํผํฐ๋ ๋ฉ์๋๋ฅผ ์ ์ํ ๋, ์ด๋ ๊ฒ ์ ์ํ ํ์ ๋๋ก ์๋์์ฑ์ด ๋๋ต๋๋ค~
associatedtype์ ์ด๋ ๊ฒ ์ค์ ์ฌ์ฉํ ํ์ ์ ์ ์ํ๊ธฐ ์ ๊น์ง ์ง์ ๋์ง ์์ผ๋ ๋ฒ์ฉ์ ์ผ๋ก ์ฌ์ฉํ ์ ์๋๋ก ํด์ฃผ๋ ์น๊ตฌ์ ๋๋ค!
์ค๋๋ ๋๊ตฐ๊ฐ์๊ฒ ๋์์ด ๋์๊ธธ ๋ฐ๋์ ๐