简体   繁体   中英

Swift - How to I define a special method for my class that returns a string representation of its object

In python if you want to define a string representation of an object you can do the following:

class Person:

    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def __str__(self):
        return f'{self.first} {self.last}, {self.age} years old'

person_1 = Person('John', 'Smith', 25)

Now, if you write print(person_1) or str(person_1) , then you get John Smith, 25 years old .

If the __str__ method didn't exist, then the output would be <__main__.Person object at 0x104e12e20>

How do I do the same thing in swift?

sure, I could define a method with whatever name I want and then call it on the object, but it would lack syntactic sugar.

Just conform to the CustomStringConvertible protocol. All you have to do is implement the description property.

struct Person: CustomStringConvertible {
    let name: String
    let age: Int

    var description: String {
        return "[name: \(name), age: \(age)]"
    }
}

print(Person(name: "bob", age: 32)) // [name: bob, age: 32]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM