Extensions in my own custom class

后端 未结 1 1103
孤独总比滥情好
孤独总比滥情好 2020-11-30 14:32

I was reading through another SO question, Swift do-try-catch syntax. In his answer, rickster creates an extension for the OP\'s custom class. Konra

相关标签:
1条回答
  • 2020-11-30 15:09

    In the case of a class that you create from scratch extensions are a powerful type of documentation through structure. You put the core of your class in the initial definition and then add on extensions to provide additional features. For example, adding adherence to a protocol. It provides locality to the contained code:

    struct Foo {
      let age: Int
    }
    
    extension Foo: CustomStringConvertible {
      var description:String { return "age: \(age)" }
    }
    

    Could I have put the protocol and computed property in the struct declaration? Absolutely but when you have more than one or two properties it starts to get messy and difficult to read. It's easier to create bugs if the code isn't clean and readable. Using extensions is a great way to stave off the difficulties that come with complexity.

    0 讨论(0)
提交回复
热议问题