CustomStringConvertible in Swift



  • Apple says: "A type with a customized textual representation. Types that conform to the CustomStringConvertible protocol can provide their own representation to be used when converting an instance to a string. The String(describing:) initializer is the preferred way to convert an instance of any type to a string"
  • CustomStringConvertible is a protocol and it's used print informative data of your object.



Ok So let's start

class Employee{
    let name: String
    let surname: String
    
    init(name: String, surname: String) {
        self.name = name
        self.surname = surname
    }
}

let emp = Employee(name: "Pawan", surname: "Manjani")
print(emp) 

  • So here if you print your class instance then it will print like below

<YourProjectName.Employee: 0x60000152b240>

  • So what we see here is not very informative, So if you want to print a readable data over here so here CustomStringConvertible will help you.



class Employee: CustomStringConvertible { 
    let name: String
    let surname: String
    
    init(name: String, surname: String) {
        self.name = name
        self.surname = surname
    }
}

//Now let's conform to CustomStringConvertible Protocol
extension Employee: CustomStringConvertible { 
    var description: String { //by implementing description property (var)
        return "My name is \(name) + " " + \(serial)"
    }
}

let emp = Employee(name: "Pawan", surname: "Manjani")
print(emp) 

  • So now if you print your class instance then it will print like below
"My name is Pawan Manjani"


Can we use CustomStringConvertible with struct??

YES 😎

Thanks for reading, Happy Coding 💻

Popular posts from this blog

Frame vs bounds in Swift

Property wrapper in Swift

DateFomatter in Swift