โš–๏ธsomeโ•ฑanyโ•ฑgenerics

โ•ฑ๐Ÿšง under construction -> homogeneous type, heterogeneous type

Swift โŸฉ type โŸฉ category โŸฉ someโ•ฑanyโ•ฑgenerics

some, any, generics ๆ˜ฏไธ‰็จฎ็‰นๆ€งไธๅŒ็š„ๅž‹ๅˆฅ๏ผŒๆฏ”่ผƒๅฆ‚ไธ‹๏ผš

็ฏ„ไพ‹

// implementer
func f() -> some Shape {
    Circle()
}

// user
let a = f()
// implementer
func g() -> any Shape {
    // omitted ...
}

// user
let b = g()
// implementer
struct Container<T> {
    var value: T
}

// user
let c = Container(value: 42)

ๅž‹ๅˆฅๆฑบๅฎš่€…

๐Ÿง‘โ€๐Ÿ’ผ ไฝฟ็”จ่€…

๐Ÿง‘โ€๐Ÿ’ผ ไฝฟ็”จ่€…

ๅž‹ๅˆฅๆฑบๅฎšๆœŸ

โš™๏ธ ็ทจ่ญฏๆœŸ

๐ŸŽ๏ธ ๅŸท่กŒๆœŸ

โš™๏ธ ็ทจ่ญฏๆœŸ

ๅ…่จฑๅคšๅž‹ๅˆฅ

ๅฆ๏ผŒๅ–ฎๅž‹ๅˆฅ (homogeneous type)

ๅฐไฝฟ็”จ่€…้šฑ่—ๅ…ท้ซ”ๅž‹ๅˆฅ๏ผŒๆ•…็จฑ็‚บ opaque typeใ€‚

ๆ˜ฏ๏ผŒๅคšๅž‹ๅˆฅ

(heterogeneous type)

ๅฐ‡ๅ…ท้ซ”ๅž‹ๅˆฅๅฐ่ฃ่ตทไพ†็š„ๅž‹ๅˆฅ๏ผŒๆ•…็จฑ็‚บ boxed protocol typeใ€‚

ไป‹ๆ–ผๆ˜ฏ่ˆ‡ๅฆไน‹้–“

ไฝฟ็”จ่€…ๅฏๆŒ‡ๅฎšไธๅŒ็š„ T๏ผŒๅ› ๆญคๅฏ็”ข็”Ÿ่จฑๅคšไธๅŒ็š„ๅ…ท้ซ”ๅž‹ๅˆฅใ€‚

ไธ้Žไธ€ๆ—ฆๆŒ‡ๅฎšไบ† T ๏ผŒๆญคๆณ›ๅž‹้ฆฌไธŠ่ฎŠ็‚บๅ–ฎๅž‹ๅˆฅ็š„ๅ…ท้ซ”ๅž‹ๅˆฅใ€‚

๐Ÿ‘‰ roles๏ผšไธๅŒ่ง’่‰ฒ(ๅฏฆ็พ่€…ใ€ไฝฟ็”จ่€…)ๅฐๅž‹ๅˆฅ็š„ไธๅŒๆŽงๅˆถๆฌŠ

๐Ÿ‘ท ๅฏฆ็พ่€… (implementer)
// custom protocol
protocol MyShape {
    func area() -> Double
}

// custom types conforming to MyShape
struct MyCircle: MyShape {
    var radius: Double
    func area() -> Double { .pi * radius * radius }
}

struct MySquare: MyShape {
    var size: Double
    func area() -> Double { size * size }
}

// return type: opaque type (some)
func makeCircle() -> some MyShape {  // โญ๏ธ ่ฟ”ๅ›žๅ€ผๅ…ท้ซ”ๅž‹ๅˆฅ๏ผš`MyCircle`
    return MyCircle(radius: 10)      // โญ๏ธ ๆฑบๅฎš่€…๏ผšๅฏฆ็พ่€…
}                                    // โญ๏ธ ๆฑบๅฎšๆœŸ๏ผš็ทจ่ญฏๆœŸ (compile time) 

// return type: boxed protocol type (any)
func makeAnyShape() -> any MyShape { // โญ๏ธ ่ฟ”ๅ›žๅ€ผๅ…ท้ซ”ๅž‹ๅˆฅ๏ผš(ๅ‹•ๆ…‹ๆฑบๅฎš)
    let n = Int.random(in: 1...6)    // โญ๏ธ ๆฑบๅฎš่€…๏ผšไฝฟ็”จ่€…
    return (n % 2 == 0)              // โญ๏ธ ๆฑบๅฎšๆœŸ๏ผšๅŸท่กŒๆœŸ (run time)
        ? MyCircle(radius: 10)      
        : MySquare(size: 4)
}                                     

// generic type
struct Container<T> {
    var value: T
}
๐Ÿง‘โ€๐Ÿ’ผ ไฝฟ็”จ่€… (user)
let shape = makeCircle()        // โญ๏ธ ไฝฟ็”จ่€…๏ผšๅช็Ÿฅ้“่ฟ”ๅ›žๅ€ผๆ˜ฏ `some MyShape`
print(shape.area())             // โญ๏ธ ไฝฟ็”จ่€…๏ผšๅฏไฝฟ็”จ `MyShape` ็š„ๆ–นๆณ•

let a = Container(value: 42)    // โญ๏ธ ๆณ›ๅž‹็š„ๅ…ท้ซ”ๅž‹ๅˆฅ๏ผš`Container<Int>`
                                // โญ๏ธ ๆฑบๅฎš่€…๏ผšไฝฟ็”จ่€…
                                // โญ๏ธ ๆฑบๅฎšๆœŸ๏ผš็ทจ่ญฏๆœŸ (compile time)

Last updated