Expressible by String Interpolation

่ฎ“ไธ€ๅ€‹ๅž‹ๅˆฅๅฏไปฅ็”จ String Interpolation ไพ†ๅˆๅง‹ๅŒ–็‰ฉไปถ (Initialization)ใ€‚

ๅ‡่จญ MyType ๆ˜ฏไธ€ๅ€‹้ตๅพช ExpressibleByStringInterpolation ็š„ๅž‹ๅˆฅ๏ผŒๅ‰‡ Swift ๆœƒๅฐ‡ไธ‹ๅˆ—้€™่กŒ็จ‹ๅผ็ขผ๏ผš

// count:        123456789012       34567
let s: MyType = "The time is \(time) now."    // interpolated literal
//               โ•ฐโ”€โ”€โ”€โ”€ L โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€Iโ”€โ”€โ•ฏโ•ฐโ”€Lโ”€โ•ฏ
// L: Literal (ๅ…ฑ 17 ๅ€‹ๅญ—ๆฏ)
// I: Interpolation (ๅ…ฑ 1 ๅ€‹)

่‡ชๅ‹•่ฝ‰ๅŒ–็‚บ๏ผš

// ---------------------------------------------------------
//     interpolated literal -> MyType.StringInterpolation
// ---------------------------------------------------------

// โญ๏ธ 1. (init) ๅ…ˆๅˆๅง‹ๅŒ–็”จไพ†็ต„ๅˆๅญ—ไธฒ็š„ interpolation ็‰ฉไปถ๏ผš
var interpolation = MyType.StringInterpolation(
    literalCapacity   : 17, 
    interpolationCount:  1
)

// โญ๏ธ 2. (configure) ๆ นๆ“šๅŽŸ interpolated literal ๅฅ—็”จ็›ธๅฐๆ‡‰็š„็ต„ๅˆๆ–นๆณ•๏ผš
//    let s: MyType = "The time is \(time) now."
//                     โ•ฐโ”€โ”€โ”€โ”€ L โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€Iโ”€โ”€โ•ฏโ•ฐโ”€Lโ”€โ•ฏ
interpolation.appendLiteral("The time is ")    // L
interpolation.appendInterpolation(time)        // I
interpolation.appendLiteral(" now.")           // L

// ---------------------------------------------------------
//     MyType.StringInterpolation -> MyType
// ---------------------------------------------------------

// โญ๏ธ 3. ไฝฟ็”จ MyType(stringInterpolation:) ๅ‚ณๅ›žๆ–ฐ็‰ฉไปถ
let s = MyType(stringInterpolation: interpolation)

ๆ•ดๅ€‹้Ž็จ‹ๅฐฑๆ˜ฏๅฐ‡ interpolated literal ่ฝ‰็‚บ MyType.StringInterpolation๏ผŒ็„ถๅพŒๅ†ๅฐ‡้€™ๅ€‹ MyType.StringInterpolation ็‰ฉไปถ่ฝ‰็‚บ MyType ๅ‚ณๅ›žใ€‚

้€™ไนŸๅฐฑๆ˜ฏ็‚บไป€้บผ็•ถๆˆ‘ๅ€‘่ฆๅฐ‡ MyType ้ตๅพชๆ–ผ ExpressibleByStringInterpolation ๅ”ๅฎšๆ™‚๏ผŒๅฟ…้ ˆๅฏฆ็พไธ‹ๅˆ—ๆขไปถ๏ผš

  • MyType.StringInterpolation (้ตๅพช StringInterpolationProtocol)๏ผš

    • .init(literalCapacity:interpolationCount:) (โญ๏ธ 1)

    • .appendLiteral()ใ€.appendInterpolation() (โญ๏ธ 2)

  • MyType๏ผš

Last updated