Custom String Interpolation

โญ๏ธ ๆณจๆ„๏ผšString.StringInterpolation == DefaultStringInterpolation

่ฎ“ String interpolation ๅฏไปฅๆ’ๅ…ฅๆ–ฐ็š„ๅž‹ๅˆฅๆˆ–่‡ช่จ‚ๆ’ๅ…ฅๆ–นๅผ๏ผš

  • extend DefaultStringInterpolation

  • add an overload of appendInterpolation(_:)

๐Ÿ‘‰ replit

let name = "Joe"
let age  = 17

// โญ๏ธ String Interpolation:
// ------------------------
// 1. String
// 2. Int
// 3. struct User
// 4. class Person

// String ๆœฌไพ†ๅฐฑ็Ÿฅ้“ๅฆ‚ไฝ•ๆ’ๅ…ฅไธ€ไบ›ๅ…งๅปบ็š„ๅž‹ๅˆฅ
"My name is \(name), I'm \(age) years old"
//          โ•ฐโ”€โ”€1โ”€โ”€โ•ฏ      โ•ฐโ”€2โ”€โ”€โ•ฏ

struct User {
    var name: String
    var age : Int
}

let joe = User(name: "Joe", age: 17)

// ๅฐฑ็ฎ—ๆ˜ฏไธ€ๅ€‹ struct๏ผŒไนŸๆฒ’ๅ•้กŒใ€‚
"Hi, I'm \(joe)"        // Hi, I'm User(name: "Joe", age: 17)
//       โ•ฐโ”€3โ”€โ”€โ•ฏ

class Person {
    var name: String = ""
    var age : Int    = 0
}

// class instance ไนŸๅฏไปฅ
let nobody = Person()
"Hi, I'm \(nobody)"     // Hi, I'm Person
//       โ•ฐโ”€โ”€ 4 โ”€โ”€โ•ฏ

// โญ๏ธ Custom String Interpolation
// -------------------------------
// ๅฆ‚ๆžœ่ฆๅฐ็‰นๅฎš็š„ๅž‹ๅˆฅๅšๅฎข่ฃฝๅŒ–็š„ String Interpolation๏ผŒ
// ๅฐฑๅฟ…้ ˆๆ“ดๅ…… DefaultStringInterpolationใ€‚

// โญ๏ธ ๆณจๆ„๏ผšString.StringInterpolation == DefaultStringInterpolation
extension String.StringInterpolation {
    mutating func appendInterpolation(_ user: User) {
        appendInterpolation("My name is \(user.name) and I'm \(user.age) years old.")
    }
}

"\(joe)"        // My name is Joe and I'm 17 years old.

Last updated