๐Ÿ”ฐroles

dev โŸฉ terms โŸฉ roles

็จ‹ๅผ้–‹็™ผไธญ็š„่ง’่‰ฒใ€‚ ๅพž้–‹็™ผ็จ‹ๅผๅˆฐไฝฟ็”จๆ‡‰็”จ็จ‹ๅผไน‹้–“ๆ‰€็‰ฝๆถ‰ๅˆฐ็š„ไบบ (ๆˆ–็จ‹ๅผ็ขผ)ใ€‚ ๐Ÿˆฏ ้€šๅธธๆŒ‡ใ€ŒๆŸไธ€ๆฎต็จ‹ๅผ็ขผใ€

่ง’่‰ฒ
่กŒ็‚บ

ๅฏฆ็พ่€…โ•ฑimplementer

ๅฏซๅ‡ฝๆ•ธใ€ๅž‹ๅˆฅๅฎš็พฉ็š„ไบบ (ๆˆ–็จ‹ๅผ็ขผ)ใ€‚

ไฝฟ็”จ่€…โ•ฑuser

ไฝฟ็”จๅ‡ฝๆ•ธใ€ๅž‹ๅˆฅๅฎš็พฉ็š„ไบบ (ๆˆ–็จ‹ๅผ็ขผ)ใ€‚

็ต‚็ซฏไฝฟ็”จ่€…โ•ฑend user

ไฝฟ็”จๆ‡‰็”จ็จ‹ๅผ็š„ไบบ (ไธๆถ‰ๅŠ็จ‹ๅผ้–‹็™ผ)ใ€‚

็ฏ„ไพ‹

// 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 ไน‹ๅพŒ๏ผŒๆญคๆณ›ๅž‹้ฆฌไธŠ่ฎŠ็‚บๅ–ฎๅž‹ๅˆฅ็š„ๅ…ท้ซ”ๅž‹ๅˆฅใ€‚

๐Ÿ‘ท ๅฏฆ็พ่€… (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