Swift protocol for string interpolation

前端 未结 3 957
时光取名叫无心
时光取名叫无心 2021-02-20 00:19

What protocol do I have to implement to control the way an object is represented within a string interpolation in Swift?

I wan\'t to specify what get\'s printed in somet

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 00:48

    In Swift 5 Apple introduced Custom String Interpolation.

    Suppose you have person struct with two properties name and age.

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

    If you wanted to add a special string interpolation for that so that we can print persons in descriptive way, we can add an extension to String.StringInterpolation with a new appendInterpolation() method.

     extension String.StringInterpolation {
           mutating func appendInterpolation(_ person: Person) {
           appendInterpolation("My name is \(person.name) and I'm \(person.age) years old.")
        }
    }
    

    Now If we print the person details like:

     let person = Person(name: "Yogendra", age: 28)
     print("Person Details: \(person)")
    

    Output will be:

    Person Details: My name is Yogendra and I'm 28 years old.
    

提交回复
热议问题